"""
Endpoints API para gestión de clases SCAII y SCAF
"""

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

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 .dto import (
    ClassCreateDTO,
    ClassCreateDTOFA,
    ClassResponseDTO,
    ClassResponseDTOFA,
    ClassUpdateDTO,
    ClassWithFADataPaginatedResponse,
)
from .service import ClassService
from api.v1.modules.a76.layouts_csv.classes.routes import router as imports_router

# Create a new router for custom endpoints
router = APIRouter()

# CSV import (upload → scan → status → commit)
router.include_router(imports_router, prefix="/imports", tags=["a76 / classes / csv_import"])

# Add consolidated catalog endpoints FIRST (before generic CRUD routes)
# This ensures they have priority over the generic /{id} route
@router.get(
    "/with-fa-data",
    response_model=ClassWithFADataPaginatedResponse,
    summary="Get Classes with FA Data",
    description="Clases con datos FA en una sola consulta (JOIN); respuesta paginada",
    tags=["a76 / classes"],
)
async def get_classes_with_fa_data(
    company_id: int = Query(..., description="Company ID"),
    page: int = Query(1, ge=1, description="Page number"),
    page_size: int = Query(50, ge=1, le=1000, description="Page size"),
    sort_by: Optional[str] = Query(None, description="Column to sort by"),
    sort_order: Optional[str] = Query("asc", description="Sort order (asc/desc)"),
    class_code: Optional[str] = Query(None, description="Filter by class code (contains)"),
    description: Optional[str] = Query(None, description="Filter by ES/EN description (contains)"),
    material_key: Optional[str] = Query(None, description="Filter by material key (contains)"),
    fraction: Optional[str] = Query(None, description="Filter by tariff fraction (contains)"),
    db: Session = Depends(get_core_db),
    current_user: Dict[str, Any] = Depends(get_current_user),
):
    """
    Get all classes with their FA data using a single LEFT JOIN query.
    This endpoint is optimized for the fixed-asset-classes view.
    """
    tenant_id = validate_access_to_resource(db, company_id, current_user, ["goods_classes.view"])
    
    skip = (page - 1) * page_size

    filters: Optional[Dict[str, Any]] = None
    if any([class_code, description, material_key, fraction]):
        filters = {}
        if class_code:
            filters["class_code"] = class_code
        if description:
            filters["description"] = description
        if material_key:
            filters["material_key"] = material_key
        if fraction:
            filters["fraction"] = fraction
    
    classes_with_fa, total = ClassService.get_all_with_fa_data(
        db=db,
        tenant_id=tenant_id,
        company_id=company_id,
        skip=skip,
        limit=page_size,
        filters=filters,
        sort_by=sort_by,
        sort_order=sort_order,
    )
    
    return ClassWithFADataPaginatedResponse(
        items=classes_with_fa,
        total=total,
        page=page,
        page_size=page_size,
    )

@router.post(
    "/fa",
    response_model=ClassResponseDTOFA,
    status_code=201,
    summary="Create Fixed Asset Class",
    description="Create a class with FA extension in a single transaction",
    tags=["a76 / classes"],
)
async def create_fa_class(
    class_data: ClassCreateDTOFA,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user: Dict[str, Any] = Depends(get_current_user),
):
    """Create a fixed asset class (both base class and FA extension)"""
    
    tenant_id = validate_access_to_resource(db, company_id, current_user, ["goods_classes.create"])
    
    result = ClassService.create_fa_class(db, class_data, tenant_id, company_id)
    
    return result

# Now include generic CRUD routes
# These will be registered AFTER the custom endpoints above
crud_router = TenantCRUDRoutes(
    service=ClassService,
    create_schema=ClassCreateDTO,
    update_schema=ClassUpdateDTO,
    response_schema=ClassResponseDTO,
    prefix="",  # No prefix here, will be added in main router
    tags=["a76 / classes"],
    resource_name="Class",
    id_name="id",
    enable_list=True,
    enable_filters=True,
    default_page_size=50,
    max_page_size=1000,
    list_permissions=["goods_classes.view"],
    create_permissions=["goods_classes.create"],
    update_permissions=["goods_classes.edit"],
    delete_permissions=["goods_classes.delete"],
).router

# Include the CRUD routes into our main router
router.include_router(crud_router)