"""
Service layer for PedimentoTransportMeans CRUD operations
"""

from typing import Optional

from sqlalchemy.orm import Session

from ..dtos.pedimento_transport_means import (
    PedimentoTransportMeansCreate,
    PedimentoTransportMeansUpdate,
)
from ..models.pedimento_transport_means import PedimentoTransportMeans


class PedimentoTransportMeansService:
    """Service class for PedimentoTransportMeans business logic"""

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

    @staticmethod
    def create(
        db: Session, data: PedimentoTransportMeansCreate
    ) -> PedimentoTransportMeans:
        """Create new transport means"""
        transport = PedimentoTransportMeans(**data.model_dump())
        db.add(transport)
        db.commit()
        db.refresh(transport)
        return transport

    @staticmethod
    def update(
        db: Session,
        pedimento_id: int,
        tenant_id: int,
        data: PedimentoTransportMeansUpdate,
    ) -> Optional[PedimentoTransportMeans]:
        """Update transport means"""
        transport = PedimentoTransportMeansService.get_by_pedimento_id(
            db, pedimento_id, tenant_id
        )
        if not transport:
            return None

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

        db.commit()
        db.refresh(transport)
        return transport

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

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