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

from fastapi import HTTPException
from sqlalchemy import or_
from sqlalchemy.orm import Session

from .models import ManifestAnexo
from .dtos import ManifestAnexoCreateDTO, ManifestAnexoUpdateDTO

logger = logging.getLogger(__name__)


class ManifestAnexoService:
    @staticmethod
    def get_all(
        db: Session,
        tenant_id: int,
        company_id: int,
        skip: int = 0,
        limit: int = 100,
        filters: Optional[Dict[str, Any]] = None,
    ) -> Tuple[List[ManifestAnexo], int]:
        query = db.query(ManifestAnexo).filter(
            ManifestAnexo.tenant_id == tenant_id,
            ManifestAnexo.company_id == company_id,
        )

        if filters:
            if filters.get("consecutive"):
                query = query.filter(ManifestAnexo.consecutive == filters["consecutive"])
            if filters.get("search"):
                search_pattern = f"%{filters['search']}%"
                query = query.filter(
                    or_(
                        ManifestAnexo.number.ilike(search_pattern),
                        ManifestAnexo.attached_doc.ilike(search_pattern),
                    )
                )

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

        return items, total

    @staticmethod
    def get_by_pk(
        db: Session, consecutive: int, line_number: int, tenant_id: int, company_id: int
    ) -> Optional[ManifestAnexo]:
        return (
            db.query(ManifestAnexo)
            .filter(
                ManifestAnexo.consecutive == consecutive,
                ManifestAnexo.line_number == line_number,
                ManifestAnexo.tenant_id == tenant_id,
                ManifestAnexo.company_id == company_id,
            )
            .first()
        )

    @staticmethod
    def create(
        db: Session,
        data: ManifestAnexoCreateDTO,
        tenant_id: int,
        company_id: int,
    ) -> ManifestAnexo:
        try:
            db_item = ManifestAnexo(
                **data.model_dump(exclude_unset=True),
                tenant_id=tenant_id,
                company_id=company_id,
            )
            db.add(db_item)
            db.commit()
            db.refresh(db_item)
            return db_item
        except Exception as e:
            db.rollback()
            logger.error(f"Error creating manifest anexo: {str(e)}")
            raise HTTPException(status_code=500, detail="Error creating manifest anexo")

    @staticmethod
    def update(
        db: Session,
        consecutive: int,
        line_number: int,
        tenant_id: int,
        company_id: int,
        data: ManifestAnexoUpdateDTO,
    ) -> Optional[ManifestAnexo]:
        item = ManifestAnexoService.get_by_pk(db, consecutive, line_number, tenant_id, company_id)
        if not item:
            return None

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

            db.commit()
            db.refresh(item)
            return item
        except Exception as e:
            db.rollback()
            logger.error(f"Error updating manifest anexo: {str(e)}")
            raise HTTPException(status_code=500, detail="Error updating manifest anexo")

    @staticmethod
    def delete(
        db: Session, consecutive: int, line_number: int, tenant_id: int, company_id: int
    ) -> bool:
        item = ManifestAnexoService.get_by_pk(db, consecutive, line_number, tenant_id, company_id)
        if not item:
            return False

        try:
            db.delete(item)
            db.commit()
            return True
        except Exception as e:
            db.rollback()
            logger.error(f"Error deleting manifest anexo: {str(e)}")
            raise HTTPException(status_code=500, detail="Error deleting manifest anexo")
