"""
Depreciation Catalog Service
"""

from sqlalchemy.orm import Session
from sqlalchemy import or_, func
from api.v1.modules.a76.general_catalogs.depreciation_catalog.models import DepreciationCatalog


class DepreciationCatalogService:
    """Service for depreciation catalog operations"""

    @staticmethod
    def get_all(
        db: Session,
        tenant_id: int,
        company_id: int,
        page: int = 1,
        page_size: int = 100,
        search: str | None = None
    ):
        """Get all depreciation catalog entries with optional search"""
        query = db.query(DepreciationCatalog).filter(
            DepreciationCatalog.tenant_id == tenant_id,
            DepreciationCatalog.company_id == company_id
        )

        # Apply search filter if provided
        if search:
            search_filter = or_(
                DepreciationCatalog.fraction.ilike(f"%{search}%"),
                DepreciationCatalog.description.ilike(f"%{search}%"),
                func.cast(DepreciationCatalog.depreciation_rate, db.String).ilike(f"%{search}%")
            )
            query = query.filter(search_filter)

        # Get total count before pagination
        total = query.count()

        # Apply pagination
        offset = (page - 1) * page_size
        items = query.order_by(
            DepreciationCatalog.fraction,
            DepreciationCatalog.depreciation_rate
        ).offset(offset).limit(page_size).all()

        return items, total

    @staticmethod
    def get_by_id(db: Session, id: int, tenant_id: int, company_id: int):
        """Get depreciation catalog entry by ID"""
        return db.query(DepreciationCatalog).filter(
            DepreciationCatalog.id == id,
            DepreciationCatalog.tenant_id == tenant_id,
            DepreciationCatalog.company_id == company_id
        ).first()

    @staticmethod
    def create(db: Session, data: dict):
        """Create new depreciation catalog entry"""
        entry = DepreciationCatalog(**data)
        db.add(entry)
        db.commit()
        db.refresh(entry)
        return entry

    @staticmethod
    def update(db: Session, id: int, tenant_id: int, company_id: int, data: dict):
        """Update depreciation catalog entry"""
        entry = DepreciationCatalogService.get_by_id(db, id, tenant_id, company_id)
        if not entry:
            return None

        for key, value in data.items():
            if value is not None:
                setattr(entry, key, value)

        db.commit()
        db.refresh(entry)
        return entry

    @staticmethod
    def delete(db: Session, id: int, tenant_id: int, company_id: int):
        """Delete depreciation catalog entry"""
        entry = DepreciationCatalogService.get_by_id(db, id, tenant_id, company_id)
        if not entry:
            return False

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