"""
Service layer for Customs Broker Concepts.
"""

from typing import Optional, Tuple, List, Dict, Any
import logging

from sqlalchemy.orm import Session
from sqlalchemy.exc import IntegrityError
from fastapi import HTTPException

from . import dto, models

logger = logging.getLogger(__name__)


class CustomsBrokerConceptService:
    """Service for Customs Broker Concept CRUD operations with tenant support"""

    @staticmethod
    def get_all(
        db: Session,
        tenant_id: int,
        company_id: int,
        skip: int = 0,
        limit: int = 50,
        filters: Optional[Dict[str, Any]] = None,
    ) -> Tuple[List[models.CustomsBrokerConcept], int]:
        """Get all customs broker concepts for a tenant/company with pagination"""
        query = db.query(models.CustomsBrokerConcept).filter(
            models.CustomsBrokerConcept.tenant_id == tenant_id,
            models.CustomsBrokerConcept.company_id == company_id,
        )

        # Apply filters if provided
        if filters:
            if filters.get("broker_key"):
                query = query.filter(
                    models.CustomsBrokerConcept.broker_key.ilike(f"%{filters['broker_key']}%")
                )
            if filters.get("concept"):
                query = query.filter(
                    models.CustomsBrokerConcept.concept.ilike(
                        f"%{filters['concept']}%")
                )

        total = query.count()
        concepts = query.offset(skip).limit(limit).all()

        return concepts, total

    @staticmethod
    def get_by_id(
        db: Session, concept_id: int, tenant_id: int, company_id: int
    ) -> Optional[models.CustomsBrokerConcept]:
        """Get customs broker concept by ID"""
        return (
            db.query(models.CustomsBrokerConcept)
            .filter(
                models.CustomsBrokerConcept.id == concept_id,
                models.CustomsBrokerConcept.tenant_id == tenant_id,
                models.CustomsBrokerConcept.company_id == company_id,
            )
            .first()
        )

    @staticmethod
    def create(
        db: Session,
        concept_data: dto.CustomsBrokerConceptCreate,
        tenant_id: int,
        company_id: int,
    ) -> models.CustomsBrokerConcept:
        """Create a new customs broker concept"""
        new_concept = models.CustomsBrokerConcept(
            **concept_data.model_dump(), tenant_id=tenant_id, company_id=company_id
        )
        db.add(new_concept)
        db.commit()
        db.refresh(new_concept)
        return new_concept

    @staticmethod
    def update(
        db: Session,
        concept_id: int,
        tenant_id: int,
        concept_data: dto.CustomsBrokerConceptUpdate,
        company_id: int,
    ) -> Optional[models.CustomsBrokerConcept]:
        """Update a customs broker concept"""
        concept = CustomsBrokerConceptService.get_by_id(
            db, concept_id, tenant_id, company_id)
        if not concept:
            return None

        # Update fields
        update_data = concept_data.model_dump(exclude_unset=True)
        for field, value in update_data.items():
            setattr(concept, field, value)

        db.commit()
        db.refresh(concept)
        return concept

    @staticmethod
    def delete(
        db: Session, concept_id: int, tenant_id: int, company_id: int
    ) -> bool:
        """Delete a customs broker concept"""
        concept = CustomsBrokerConceptService.get_by_id(
            db, concept_id, tenant_id, company_id)
        if not concept:
            return False

        try:
            db.delete(concept)
            db.commit()
            return True
        except IntegrityError as e:
            db.rollback()
            logger.error(f"IntegrityError deleting concept {concept_id}: {str(e)}")
            if "foreign key constraint" in str(e).lower():
                raise HTTPException(
                    status_code=400, 
                    detail="No se puede eliminar el concepto porque tiene registros relacionados"
                )
            raise HTTPException(status_code=400, detail="Error al eliminar el concepto")
        except Exception as e:
            db.rollback()
            logger.error(f"Error deleting concept {concept_id}: {str(e)}")
            raise HTTPException(status_code=500, detail="Error al eliminar el concepto")
