"""
Service layer for PedimentoCustomsOffices CRUD operations
"""

from typing import Optional

from sqlalchemy.orm import Session

from ..dtos.pedimento_customs_offices import (
    PedimentoCustomsOfficesCreate,
    PedimentoCustomsOfficesUpdate,
)
from ..models.pedimento_customs_offices import PedimentoCustomsOffices


class PedimentoCustomsOfficesService:
    """Service class for PedimentoCustomsOffices business logic"""

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

    @staticmethod
    def create(
        db: Session, data: PedimentoCustomsOfficesCreate
    ) -> PedimentoCustomsOffices:
        """Create new customs offices"""
        offices = PedimentoCustomsOffices(**data.model_dump())
        db.add(offices)
        db.commit()
        db.refresh(offices)
        return offices

    @staticmethod
    def update(
        db: Session,
        pedimento_id: int,
        tenant_id: int,
        data: PedimentoCustomsOfficesUpdate,
    ) -> Optional[PedimentoCustomsOffices]:
        """Update customs offices"""
        offices = PedimentoCustomsOfficesService.get_by_pedimento_id(
            db, pedimento_id, tenant_id
        )
        if not offices:
            return None

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

        db.commit()
        db.refresh(offices)
        return offices

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

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