"""
Service layer for Packages (GBultos).
"""

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 PackageService:
    """Service for Package 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.Package], int]:
        """Get all packages for a tenant/company with pagination"""
        query = db.query(models.Package).filter(
            models.Package.tenant_id == tenant_id,
            models.Package.company_id == company_id,
        )

        # Apply filters if provided
        if filters:
            if filters.get("key"):
                query = query.filter(
                    models.Package.key.ilike(f"%{filters['key']}%")
                )
            if filters.get("description_es"):
                query = query.filter(
                    models.Package.description_es.ilike(
                        f"%{filters['description_es']}%")
                )

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

        return packages, total

    @staticmethod
    def get_by_id(
        db: Session, package_id: int, tenant_id: int, company_id: int
    ) -> Optional[models.Package]:
        """Get package by ID"""
        return (
            db.query(models.Package)
            .filter(
                models.Package.id == package_id,
                models.Package.tenant_id == tenant_id,
                models.Package.company_id == company_id,
            )
            .first()
        )

    @staticmethod
    def create(
        db: Session,
        package_data: dto.PackageCreateDTO,
        tenant_id: int,
        company_id: int,
    ) -> models.Package:
        """Create a new package"""
        new_package = models.Package(
            **package_data.model_dump(), tenant_id=tenant_id, company_id=company_id
        )
        db.add(new_package)
        db.commit()
        db.refresh(new_package)
        return new_package

    @staticmethod
    def update(
        db: Session,
        package_id: int,
        tenant_id: int,
        package_data: dto.PackageUpdateDTO,
        company_id: int,
    ) -> Optional[models.Package]:
        """Update a package"""
        package = PackageService.get_by_id(
            db, package_id, tenant_id, company_id)
        if not package:
            return None

        # Update fields (excluding key if it's meant to be immutable)
        update_data = package_data.model_dump(
            exclude_unset=True, exclude={"key"})
        for field, value in update_data.items():
            setattr(package, field, value)

        db.commit()
        db.refresh(package)
        return package

    @staticmethod
    def delete(
        db: Session, package_id: int, tenant_id: int, company_id: int
    ) -> bool:
        """Delete a package"""
        package = PackageService.get_by_id(
            db, package_id, tenant_id, company_id)
        if not package:
            return False

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