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 PedimentoTransportCatalogDTO
from .models import PedimentoTransportCatalog
from ..rbac import require_ref_view

router = APIRouter(prefix="/pedimento-transport-catalog")


@router.get(
    "/",
    response_model=Dict[str, Any],
    dependencies=[Depends(require_ref_view("ref_transport_types.view"))],
)
async def list_pedimento_transport_catalog(
    page: int = Query(1, ge=1, description="Numero de pagina"),
    page_size: int = Query(100, ge=1, le=200, description="Tamano de pagina"),
    search: str = Query(None, description="Término de búsqueda"),
    db: Session = Depends(get_core_db),
):
    skip = (page - 1) * page_size
    query = db.query(PedimentoTransportCatalog)
    
    if search:
        search_filter = f"%{search}%"
        query = query.filter(
            or_(
                PedimentoTransportCatalog.code.ilike(search_filter),
                PedimentoTransportCatalog.transport_en.ilike(search_filter),
                PedimentoTransportCatalog.transport_es.ilike(search_filter),
                PedimentoTransportCatalog.payment_date_code.ilike(search_filter)
            )
        ).order_by(PedimentoTransportCatalog.code.asc())
    items = query.offset(skip).limit(page_size).all()
    total = query.count()
    return {
        "items": [PedimentoTransportCatalogDTO.model_validate(obj) for obj in items],
        "total": total,
        "page": page,
        "page_size": page_size,
    }


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


@router.post("/", response_model=PedimentoTransportCatalogDTO, status_code=201)
async def create_pedimento_transport_catalog(
    data: PedimentoTransportCatalogDTO,
    db: Session = Depends(get_core_db),
    user=Depends(get_current_user),
):
    obj = PedimentoTransportCatalog(**data.model_dump())
    db.add(obj)
    db.commit()
    db.refresh(obj)
    return obj


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


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