"""
Service layer for PedimentoDecrementables CRUD operations
"""

from typing import Optional

from sqlalchemy.orm import Session

from ..dtos.pedimento_decrementables import (
    PedimentoDecrementablesCreate,
    PedimentoDecrementablesUpdate,
)
from ..models.pedimento_decrementables import PedimentoDecrementables


class PedimentoDecrementablesService:
    """Service class for PedimentoDecrementables business logic"""

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

    @staticmethod
    def create(
        db: Session, data: PedimentoDecrementablesCreate
    ) -> PedimentoDecrementables:
        """Create new decrementables"""
        decrementables = PedimentoDecrementables(**data.model_dump())
        db.add(decrementables)
        db.commit()
        db.refresh(decrementables)
        return decrementables

    @staticmethod
    def update(
        db: Session,
        pedimento_id: int,
        tenant_id: int,
        data: PedimentoDecrementablesUpdate,
    ) -> Optional[PedimentoDecrementables]:
        """Update decrementables"""
        decrementables = PedimentoDecrementablesService.get_by_pedimento_id(
            db, pedimento_id, tenant_id
        )
        if not decrementables:
            return None

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

        db.commit()
        db.refresh(decrementables)
        return decrementables

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

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