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

from typing import Dict, Any, List
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, ClassWithFADataResponse
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=List[ClassWithFADataResponse],
    summary="Get Classes with FA Data",
    description="Get all classes with their FA data in a single query (eliminates N+1 problem)",
    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(1000, ge=1, le=1000, description="Page size"),
    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)
    
    skip = (page - 1) * page_size
    
    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,
    )
    
    return classes_with_fa

@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)
    
    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,
).router

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