"""
Routes for Pedimentos CRUD operations
"""

from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session

from api.v1.common.tenant_crud_routes import TenantCRUDRoutes
from core.database import get_core_db
from core.security import get_current_user

from ..dtos.pedimentos import PedimentosCreate, PedimentosResponse, PedimentosUpdate
from ..services.pedimentos import PedimentosService
from ..catalog_service import PedimentoCatalogService
from ..schemas import PedimentoCreationResponse, PedimentoEditionResponse

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

# Add consolidated catalog endpoints FIRST (before generic CRUD routes)
# This ensures they have priority over the generic /{id} route
@router.get("/creation-data", response_model=PedimentoCreationResponse, tags=["a76 / pedimentos"])
async def get_creation_data(
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(get_current_user)
):
    """
    Get all catalogs needed for creating a new pedimento.
    Consolidates multiple catalog calls into a single endpoint.
    """
    from core.security import validate_access_to_resource
    # Alta de pedimento: requiere permiso create.
    validate_access_to_resource(db, company_id, current_user, ["pedimentos_mgmt.create"])

    tenant_id = current_user["tenant_id"]
    
    try:
        return PedimentoCatalogService.get_creation_data(db, tenant_id, company_id)
    except HTTPException:
        raise
    except Exception as e:
        print(f"Error fetching creation data: {e}")
        import traceback
        traceback.print_exc()
        raise HTTPException(status_code=500, detail="Error fetching creation data")


@router.get("/{pedimento_id}/edition-data", response_model=PedimentoEditionResponse, tags=["a76 / pedimentos"])
async def get_edition_data(
    pedimento_id: int,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(get_current_user)
):
    """
    Get all catalogs and pedimento data needed for editing an existing pedimento.
    Consolidates multiple catalog calls + pedimento fetch into a single endpoint.
    """
    from core.security import validate_access_to_resource
    validate_access_to_resource(db, company_id, current_user, ["pedimentos_mgmt.edit"])

    tenant_id = current_user["tenant_id"]
    
    try:
        result = PedimentoCatalogService.get_edition_data(db, pedimento_id, tenant_id, company_id)
        
        if result is None:
            raise HTTPException(status_code=404, detail="Pedimento not found")
            
        return result
    except HTTPException:
        raise
    except Exception as e:
        print(f"Error fetching edition data: {e}")
        import traceback
        traceback.print_exc()
        raise HTTPException(status_code=500, detail="Error fetching edition data")


# Now include generic CRUD routes
# These will be registered AFTER the custom endpoints above
crud_router = TenantCRUDRoutes(
    service=PedimentosService,
    create_schema=PedimentosCreate,
    update_schema=PedimentosUpdate,
    response_schema=PedimentosResponse,
    prefix="",  # No prefix here, will be added in main router
    tags=["a76 / pedimentos"],  # Tag for Swagger documentation
    resource_name="Pedimento",
    id_name="id",  # Use standard REST convention
    enable_list=True,  # Enable GET / with pagination
    enable_filters=True,  # Enable status, client_id, year filters
    default_page_size=50,
    max_page_size=1000,
    list_permissions=["pedimentos_mgmt.view"],
    get_permissions=["pedimentos_mgmt.view"],
    create_permissions=["pedimentos_mgmt.create"],
    update_permissions=["pedimentos_mgmt.edit"],
    delete_permissions=["pedimentos_mgmt.delete"],
).router

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