"""
Depreciation Catalog Routes
"""

from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session
from typing import Any, Dict, Optional

from core.database import get_core_db
from core.security import get_current_user
from api.v1.common.tenant_crud_routes import TenantCRUDRoutes, validate_access_to_resource
from api.v1.modules.a76.general_catalogs.depreciation_catalog.service import DepreciationCatalogService
from api.v1.modules.a76.general_catalogs.depreciation_catalog.dto import (
    DepreciationCatalogCreate,
    DepreciationCatalogUpdate,
    DepreciationCatalogResponse
)

# Create base router with generic CRUD routes (disabled list because we'll create a custom one)
base_router = TenantCRUDRoutes(
    service=DepreciationCatalogService,
    create_schema=DepreciationCatalogCreate,
    update_schema=DepreciationCatalogUpdate,
    response_schema=DepreciationCatalogResponse,
    prefix="/depreciation-catalog",
    tags=["a76 / general catalogs / depreciation catalog"],
    resource_name="DepreciationCatalog",
    id_name="depreciation_catalog_id",
    enable_list=False,  # Disable default list, we'll add custom one
    enable_filters=False,
    default_page_size=100,
    max_page_size=1000,
    get_permissions=["cat_depreciation_catalog.view"],
    create_permissions=["cat_depreciation_catalog.create"],
    update_permissions=["cat_depreciation_catalog.edit"],
    delete_permissions=["cat_depreciation_catalog.delete"],
)

router = APIRouter(prefix="/depreciation-catalog", tags=["a76 / general catalogs / depreciation catalog"])

# Custom list endpoint with search filter
@router.get(
    "/",
    response_model=Dict[str, Any],
    summary="List Depreciation Catalog",
    description="Get paginated list of Depreciation Catalog entries with optional search filter",
)
async def list_depreciation_catalog(
    company_id: int = Query(..., description="Company ID"),
    page: int = Query(1, ge=1, description="Page number"),
    page_size: int = Query(100, ge=1, le=1000, description="Page size"),
    search: Optional[str] = Query(None, description="Search in fraction or description"),
    db: Session = Depends(get_core_db),
    current_user: Dict[str, Any] = Depends(get_current_user),
):
    tenant_id = validate_access_to_resource(
        db, company_id, current_user, ["cat_depreciation_catalog.view"]
    )
    
    items, total = DepreciationCatalogService.get_all(
        db, tenant_id, company_id, page, page_size, search
    )
    
    return {
        "items": [DepreciationCatalogResponse.model_validate(item) for item in items],
        "total": total,
        "page": page,
        "page_size": page_size,
        "pages": (total + page_size - 1) // page_size,
    }

# Include other CRUD routes from base router
router.include_router(base_router.router)
