from typing import Any, Dict

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

from . import dto, services
from ..rbac import require_ref_view

router = APIRouter()


@router.get(
    "/trailer-types/",
    response_model=Dict[str, Any],
    dependencies=[Depends(require_ref_view("trailers.view"))],
)
def list_trailer_types(
    page: int = Query(1, ge=1, description="Número de página"),
    page_size: int = Query(50, ge=1, le=100, description="Tamaño de página"),
    search: str = Query(None, description="Término de búsqueda"),
    db: Session = Depends(get_core_db),
):
    skip = (page - 1) * page_size
    items, total = services.TrailerTypeService.list_trailer_types(db, skip, page_size, search)
    return {
        "items": [dto.TrailerTypeListItemDTO.model_validate(obj) for obj in items],
        "total": total,
        "page": page,
        "page_size": page_size,
    }


@router.get(
    "/trailer-types/{trailer_type_key}",
    response_model=dto.TrailerTypeResponseDTO,
    dependencies=[Depends(require_ref_view("trailers.view"))],
)
def get_trailer_type(trailer_type_key: str, db: Session = Depends(get_core_db)):
    trailer_type = services.TrailerTypeService.get_trailer_type_by_key(
        db, trailer_type_key
    )
    if not trailer_type:
        raise HTTPException(status_code=404, detail="Trailer type not found")
    return trailer_type


@router.post("/trailer-types", response_model=dto.TrailerTypeResponseDTO)
def create_trailer_type(
    trailer_type_data: dto.TrailerTypeCreateDTO, db: Session = Depends(get_core_db)
):
    return services.TrailerTypeService.create_trailer_type(db, trailer_type_data)


@router.delete(
    "/trailer-types/{trailer_type_key}", response_model=dto.TrailerTypeResponseDTO
)
def delete_trailer_type(trailer_type_key: str, db: Session = Depends(get_core_db)):
    trailer_type = services.TrailerTypeService.delete_trailer_type(db, trailer_type_key)
    if not trailer_type:
        raise HTTPException(status_code=404, detail="Trailer type not found")
    return trailer_type
