"""
Service layer for PedimentoConfigAdditional CRUD operations
"""

from typing import Optional

from sqlalchemy.orm import Session

from ..dtos.pedimento_config_additional import (
    PedimentoConfigAdditionalCreate,
    PedimentoConfigAdditionalUpdate,
)
from ..models.pedimento_config_additional import PedimentoConfigAdditional


class PedimentoConfigAdditionalService:
    """Service class for PedimentoConfigAdditional business logic"""

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

    @staticmethod
    def create(
        db: Session,
        config_data: PedimentoConfigAdditionalCreate,
        tenant_id: int,
        company_id: int,
    ) -> PedimentoConfigAdditional:
        """Create a new config"""
        config = PedimentoConfigAdditional(**config_data.model_dump())
        config.tenant_id = tenant_id
        config.company_id = company_id

        db.add(config)
        db.commit()
        db.refresh(config)
        return config

    @staticmethod
    def update(
        db: Session,
        pedimento_id: int,
        tenant_id: int,
        company_id: int,
        config_data: PedimentoConfigAdditionalUpdate,
    ) -> Optional[PedimentoConfigAdditional]:
        """Update config"""
        config = PedimentoConfigAdditionalService.get_by_pedimento_id(
            db, pedimento_id, tenant_id, company_id
        )
        if not config:
            return None

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

        db.commit()
        db.refresh(config)
        return config

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

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