"""
Rutas para el catálogo de claves FDA
"""
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from typing import Any, Dict, Optional
from api.v1.modules.a76.general_catalogs.fda_catalog.service import FDACatalogService
from api.v1.modules.a76.general_catalogs.fda_catalog.dto import FDACatalogResponse
from core.database import get_core_db
from core.security import get_current_user
from api.v1.common.tenant_crud_routes import validate_access_to_resource


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


@router.get("/")
async def list_fda_catalog(
    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"),
    search: Optional[str] = Query(None, description="Search in FDA key, description or code"),
    db: Session = Depends(get_core_db),
    current_user: Dict[str, Any] = Depends(get_current_user)
):
    """Listar entradas del catálogo FDA con búsqueda y paginación"""
    tenant_id = validate_access_to_resource(db, company_id, current_user)
    
    filters = {"search": search} if search else {}
    result = FDACatalogService.get_all(db, tenant_id, company_id, page, page_size, filters)
    
    return {
        "items": result["items"],
        "total": result["total"],
        "page": result["page"],
        "page_size": result["page_size"],
        "pages": result["pages"]
    }


@router.get("/{id}")
async def get_fda_catalog(
    id: int,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user: Dict[str, Any] = Depends(get_current_user)
):
    """Obtener una entrada del catálogo FDA por ID"""
    tenant_id = validate_access_to_resource(db, company_id, current_user)
    
    entry = FDACatalogService.get_by_id(db, tenant_id, company_id, id)
    if not entry:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Entrada no encontrada")
    
    return {
        "id": entry.id,
        "fda_key": entry.fda_key,
        "description": entry.description,
        "fda_code": entry.fda_code,
        "requirements": entry.requirements,
        "manufacturer_number": entry.manufacturer_number,
        "country_of_production": entry.country_of_production,
        "storage_status": entry.storage_status,
        "warehouse_code": entry.warehouse_code,
        "call_atl": entry.call_atl
    }
