"""
Service layer for PedimentoRectificationDestination CRUD operations
"""

from typing import Optional

from sqlalchemy.orm import Session

from ..dtos.pedimento_rectification_destination import (
    PedimentoRectificationDestinationCreate,
    PedimentoRectificationDestinationUpdate,
)
from ..models.pedimento_rectification_destination import (
    PedimentoRectificationDestination,
)


class PedimentoRectificationDestinationService:
    """Service class for PedimentoRectificationDestination business logic"""

    @staticmethod
    def get_by_pedimento_id(
        db: Session, pedimento_id: int, tenant_id: int, company_id: int = None
    ) -> Optional[PedimentoRectificationDestination]:
        """Get rectification destination by pedimento ID"""
        return (
            db.query(PedimentoRectificationDestination)
            .filter(
                PedimentoRectificationDestination.pedimento_id == pedimento_id,
                PedimentoRectificationDestination.tenant_id == tenant_id,
                PedimentoRectificationDestination.company_id == company_id,
            )
            .first()
        )

    @staticmethod
    def create(
        db: Session, data: PedimentoRectificationDestinationCreate
    ) -> PedimentoRectificationDestination:
        """Create new rectification destination"""
        rectification = PedimentoRectificationDestination(**data.model_dump())
        db.add(rectification)
        db.commit()
        db.refresh(rectification)
        return rectification

    @staticmethod
    def update(
        db: Session,
        pedimento_id: int,
        tenant_id: int,
        data: PedimentoRectificationDestinationUpdate,
    ) -> Optional[PedimentoRectificationDestination]:
        """Update rectification destination"""
        rectification = PedimentoRectificationDestinationService.get_by_pedimento_id(
            db, pedimento_id, tenant_id
        )
        if not rectification:
            return None

        update_data = data.model_dump(exclude_unset=True)
        for field, value in update_data.items():
            setattr(rectification, field, value)

        db.commit()
        db.refresh(rectification)
        return rectification

    @staticmethod
    def delete(db: Session, pedimento_id: int, tenant_id: int) -> bool:
        """Delete rectification destination"""
        rectification = PedimentoRectificationDestinationService.get_by_pedimento_id(
            db, pedimento_id, tenant_id
        )
        if not rectification:
            return False

        db.delete(rectification)
        db.commit()
        return True
