"""
Service layer for PedimentoConfigCalculations CRUD operations
"""

from typing import Optional

from sqlalchemy.orm import Session

from ..dtos.pedimento_config_calculations import (
    PedimentoConfigCalculationsCreate,
    PedimentoConfigCalculationsUpdate,
)
from ..models.pedimento_config_calculations import PedimentoConfigCalculations


class PedimentoConfigCalculationsService:
    """Service class for PedimentoConfigCalculations business logic"""

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

    @staticmethod
    def create(
        db: Session,
        config_data: PedimentoConfigCalculationsCreate,
        tenant_id: int,
        company_id: int,
    ) -> PedimentoConfigCalculations:
        """Create a new config"""
        config = PedimentoConfigCalculations(**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: PedimentoConfigCalculationsUpdate,
    ) -> Optional[PedimentoConfigCalculations]:
        """Update config"""
        config = PedimentoConfigCalculationsService.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 = PedimentoConfigCalculationsService.get_by_pedimento_id(
            db, pedimento_id, tenant_id, company_id
        )
        if not config:
            return False

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