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 ValueManifestation
from .dtos import (
    ValueManifestationCreateDTO,
    ValueManifestationUpdateDTO,
)

logger = logging.getLogger(__name__)


class ValueManifestationService:
    @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[ValueManifestation], int]:
        query = db.query(ValueManifestation).filter(
            ValueManifestation.tenant_id == tenant_id,
            ValueManifestation.company_id == company_id,
        )

        if filters:
            if filters.get("search"):
                search_pattern = f"%{filters['search']}%"
                query = query.filter(
                    or_(
                        ValueManifestation.manifestation_number.ilike(search_pattern),
                        ValueManifestation.pedimento.ilike(search_pattern),
                    )
                )

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

        return items, total

    @staticmethod
    def get_by_id(
        db: Session,
        value_manifestation_id: int,
        tenant_id: int,
        company_id: int,
    ) -> Optional[ValueManifestation]:
        return (
            db.query(ValueManifestation)
            .filter(
                ValueManifestation.id == value_manifestation_id,
                ValueManifestation.tenant_id == tenant_id,
                ValueManifestation.company_id == company_id,
            )
            .first()
        )

    @staticmethod
    def create(
        db: Session,
        data: ValueManifestationCreateDTO,
        tenant_id: int,
        company_id: int,
    ) -> ValueManifestation:
        try:
            db_item = ValueManifestation(
                **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 value manifestation: {str(e)}")
            raise HTTPException(
                status_code=500, detail="Error creating value manifestation"
            )

    @staticmethod
    def update(
        db: Session,
        value_manifestation_id: int,
        tenant_id: int,
        company_id: int,
        data: ValueManifestationUpdateDTO,
    ) -> Optional[ValueManifestation]:
        item = ValueManifestationService.get_by_id(
            db, value_manifestation_id, 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 value manifestation {value_manifestation_id}: {str(e)}")
            raise HTTPException(
                status_code=500, detail="Error updating value manifestation"
            )

    @staticmethod
    def delete(
        db: Session, value_manifestation_id: int, tenant_id: int, company_id: int
    ) -> bool:
        item = ValueManifestationService.get_by_id(
            db, value_manifestation_id, 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 value manifestation {value_manifestation_id}: {str(e)}")
            raise HTTPException(
                status_code=500, detail="Error deleting value manifestation"
            )
