"""
Service layer for PedimentoRectificationOrigin CRUD operations
"""

from typing import Optional

from sqlalchemy.orm import Session

from ..dtos.pedimento_rectification_origin import (
    PedimentoRectificationOriginCreate,
    PedimentoRectificationOriginUpdate,
)
from ..models.pedimento_rectification_origin import PedimentoRectificationOrigin


class PedimentoRectificationOriginService:
    """Service class for PedimentoRectificationOrigin business logic"""

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

    @staticmethod
    def create(
        db: Session, data: PedimentoRectificationOriginCreate
    ) -> PedimentoRectificationOrigin:
        """Create new rectification origin"""
        rectification = PedimentoRectificationOrigin(**data.model_dump())
        db.add(rectification)
        db.commit()
        db.refresh(rectification)
        return rectification

    @staticmethod
    def update(
        db: Session,
        pedimento_id: int,
        tenant_id: int,
        data: PedimentoRectificationOriginUpdate,
    ) -> Optional[PedimentoRectificationOrigin]:
        """Update rectification origin"""
        rectification = PedimentoRectificationOriginService.get_by_pedimento_id(
            db, pedimento_id, tenant_id
        )
        if not rectification:
            return None

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

        db.commit()
        db.refresh(rectification)
        return rectification

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

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