"""
Service layer for PedimentoConfigUpdateRectification CRUD operations
"""

from typing import Optional

from sqlalchemy.orm import Session

from ..dtos.pedimento_config_update_rectification import (
    PedimentoConfigUpdateRectificationCreate,
    PedimentoConfigUpdateRectificationUpdate,
)
from ..models.pedimento_config_update_rectification import (
    PedimentoConfigUpdateRectification,
)


class PedimentoConfigUpdateRectificationService:
    """Service class for PedimentoConfigUpdateRectification business logic"""

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

    @staticmethod
    def create(
        db: Session, config_data: PedimentoConfigUpdateRectificationCreate
    ) -> PedimentoConfigUpdateRectification:
        """Create a new config"""
        config = PedimentoConfigUpdateRectification(**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: PedimentoConfigUpdateRectificationUpdate,
    ) -> Optional[PedimentoConfigUpdateRectification]:
        """Update config"""
        config = PedimentoConfigUpdateRectificationService.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 = PedimentoConfigUpdateRectificationService.get_by_pedimento_id(
            db, pedimento_id, tenant_id
        )
        if not config:
            return False

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