from typing import Any, Dict

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

from .dto import TransportTypeDTO
from .models import TransportType
from ..rbac import require_ref_view

router = APIRouter(prefix="/transport-types")


@router.get(
    "/",
    response_model=Dict[str, Any],
    dependencies=[Depends(require_ref_view("ref_transport_types.view"))],
)
def list_transport_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
    query = db.query(TransportType)
    
    if search:
        search_filter = f"%{search}%"
        query = query.filter(
            or_(
                TransportType.transport_code.ilike(search_filter),
                TransportType.description.ilike(search_filter)
            )
        )
    items = query.offset(skip).limit(page_size).all()
    total = query.count()
    return {
        "items": [TransportTypeDTO.model_validate(obj) for obj in items],
        "total": total,
        "page": page,
        "page_size": page_size,
    }


@router.get(
    "/{transport_code}",
    response_model=TransportTypeDTO,
    dependencies=[Depends(require_ref_view("ref_transport_types.view"))],
)
def get_transport_type(transport_code: str, db: Session = Depends(get_core_db)):
    obj = (
        db.query(TransportType)
        .filter(TransportType.transport_code == transport_code)
        .first()
    )
    if not obj:
        raise HTTPException(status_code=404, detail="Not found")
    return obj


@router.post("/", response_model=TransportTypeDTO, status_code=201)
def create_transport_type(
    data: TransportTypeDTO,
    db: Session = Depends(get_core_db),
    user=Depends(get_current_user),
):
    obj = TransportType(**data.dict())
    db.add(obj)
    db.commit()
    db.refresh(obj)
    return obj


@router.put("/{transport_code}", response_model=TransportTypeDTO)
def update_transport_type(
    transport_code: str,
    data: TransportTypeDTO,
    db: Session = Depends(get_core_db),
    user=Depends(get_current_user),
):
    obj = (
        db.query(TransportType)
        .filter(TransportType.transport_code == transport_code)
        .first()
    )
    if not obj:
        raise HTTPException(status_code=404, detail="Not found")
    for field, value in data.dict().items():
        setattr(obj, field, value)
    db.commit()
    db.refresh(obj)
    return obj


@router.delete("/{transport_code}", status_code=204)
def delete_transport_type(
    transport_code: str,
    db: Session = Depends(get_core_db),
    user=Depends(get_current_user),
):
    obj = (
        db.query(TransportType)
        .filter(TransportType.transport_code == transport_code)
        .first()
    )
    if not obj:
        raise HTTPException(status_code=404, detail="Not found")
    db.delete(obj)
    db.commit()
    return None
