"""
Service layer for PedimentoConfigUpdates CRUD operations
"""

from typing import Optional

from sqlalchemy.orm import Session

from ..dtos.pedimento_config_updates import (
    PedimentoConfigUpdatesCreate,
    PedimentoConfigUpdatesUpdate,
)
from ..models.pedimento_config_updates import PedimentoConfigUpdates


class PedimentoConfigUpdatesService:
    """Service class for PedimentoConfigUpdates business logic"""

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

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

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