from typing import Any, Dict

from core.database import get_core_db
from core.security import get_current_user, has_role
from fastapi import APIRouter, Depends, HTTPException, Query
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy import or_
from sqlalchemy.orm import Session

from .dto import CartaPorteDTO
from .models import CartaPorte
from ..rbac import require_ref_view

router = APIRouter(prefix="/carta-porte")


@router.get(
    "/",
    response_model=Dict[str, Any],
    dependencies=[Depends(require_ref_view("ref_transport_types.view"))],
)
async def list_carta_porte(
    page: int = Query(1, ge=1),
    page_size: int = Query(50, ge=1, le=100),
    q: str = Query(None, description="Buscar por código o descripción"),
    search: str = Query(None, description="Término de búsqueda"),
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(get_current_user),
):
    skip = (page - 1) * page_size
    query = db.query(CartaPorte)
    
    if search:
        search_filter = f"%{search}%"
        query = query.filter(
            or_(
                CartaPorte.code.ilike(search_filter),
                CartaPorte.description.ilike(search_filter)
            )
        )
    
    if q:
        search_filter = f"%{q}%"
        query = query.filter(
            or_(
                CartaPorte.code.ilike(search_filter),
                CartaPorte.description.ilike(search_filter),
                CartaPorte.similar_words.ilike(search_filter)
            )
        )
    
    total = query.count()
    items = query.offset(skip).limit(page_size).all()
    
    return {
        "items": [CartaPorteDTO.model_validate(obj) for obj in items],
        "total": total,
        "page": page,
        "page_size": page_size,
    }


@router.get(
    "/{id}",
    response_model=CartaPorteDTO,
    dependencies=[Depends(require_ref_view("ref_transport_types.view"))],
)
async def get_carta_porte(
    id: int,
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(get_current_user),
):
    obj = db.query(CartaPorte).filter(CartaPorte.id == id).first()
    if not obj:
        raise HTTPException(status_code=404, detail="Not found")
    return obj
