"""
Service layer for PedimentoConfigSurcharges CRUD operations
"""

from typing import Optional

from sqlalchemy.orm import Session

from ..dtos.pedimento_config_surcharges import (
    PedimentoConfigSurchargesCreate,
    PedimentoConfigSurchargesUpdate,
)
from ..models.pedimento_config_surcharges import PedimentoConfigSurcharges


class PedimentoConfigSurchargesService:
    """Service class for PedimentoConfigSurcharges business logic"""

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

    @staticmethod
    def create(
        db: Session, config_data: PedimentoConfigSurchargesCreate
    ) -> PedimentoConfigSurcharges:
        """Create a new config"""
        config = PedimentoConfigSurcharges(**config_data.model_dump())
        db.add(config)
        db.commit()
        db.refresh(config)
        return config

    @staticmethod
    def update(
        db: Session,
        pedimento_id: int,
        tenant_id: int,
        config_data: PedimentoConfigSurchargesUpdate,
    ) -> Optional[PedimentoConfigSurcharges]:
        """Update config"""
        config = PedimentoConfigSurchargesService.get_by_pedimento_id(
            db, pedimento_id, tenant_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) -> bool:
        """Delete config"""
        config = PedimentoConfigSurchargesService.get_by_pedimento_id(
            db, pedimento_id, tenant_id
        )
        if not config:
            return False

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