"""
Endpoints API para fracciones arancelarias americanas
"""

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 (
    USTariffFractionCreateDTO,
    USTariffFractionResponseDTO,
    USTariffFractionUpdateDTO,
)
from .service import USTariffFractionService

# Create router using TenantCRUDRoutes factory for basic CRUD operations (prefix="" so we mount under main_router)
crud_router = TenantCRUDRoutes(
    service=USTariffFractionService,
    create_schema=USTariffFractionCreateDTO,
    update_schema=USTariffFractionUpdateDTO,
    response_schema=USTariffFractionResponseDTO,
    prefix="",
    tags=["a76 / general catalogs / us tariff fractions"],
    resource_name="US Tariff Fraction",
    id_name="id",
    enable_list=False, # We implement our custom list endpoint
)

# Master router with prefix so all routes live under /us-tariff-fractions
from api.v1.modules.a76.layouts_csv.us_tariff_fractions.routes import router as imports_router
main_router = APIRouter(prefix="/us-tariff-fractions", tags=["a76 / general catalogs / us tariff fractions"])
main_router.include_router(imports_router, prefix="/imports", tags=["us_tariff_fractions / csv_import"])
main_router.include_router(crud_router.router)


# Custom list endpoint with search filter (under /us-tariff-fractions/)
@main_router.get(
    "/",
    response_model=Dict[str, Any],
    summary="List US Tariff Fractions",
    description="Get paginated list of US Tariff Fractions with optional search filter",
)
async def list_us_tariff_fractions(
    company_id: int = Query(..., description="Company ID"),
    page: int = Query(1, ge=1, description="Page number"),
    page_size: int = Query(50, ge=1, le=10000, description="Page size"),
    search: Optional[str] = Query(None, description="Search in code, description, or prefix"),
    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)
    
    skip = (page - 1) * page_size
    filters = {}
    if search:
        filters["search"] = search
    
    items, total = await USTariffFractionService.get_all(
        db, tenant_id, company_id, skip, page_size, filters
    )
    
    return {
        "items": [USTariffFractionResponseDTO.model_validate(item) for item in items],
        "total": total,
        "page": page,
        "page_size": page_size,
        "pages": (total + page_size - 1) // page_size,
    }


router = main_router
