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 sqlalchemy.orm import Session
from sqlalchemy import or_

from .dto import IncotermDTO
from .models import Incoterm
from ..rbac import require_ref_view

router = APIRouter(prefix="/incoterms")


@router.get(
    "/",
    response_model=Dict[str, Any],
    dependencies=[Depends(require_ref_view("ref_incoterms.view"))],
)
async def list_incoterms(
    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"),
    code: str = Query(None, description="Filtrar por clave"),
    description: str = Query(None, description="Filtrar por 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(Incoterm)
    
    if search:
        search_filter = f"%{search}%"
        query = query.filter(
            or_(
                Incoterm.code.ilike(search_filter),
                Incoterm.description_es.ilike(search_filter),
                Incoterm.description_en.ilike(search_filter)
            )
        )
    
    if code:
        query = query.filter(Incoterm.code.ilike(f"%{code}%"))
    if description:
        query = query.filter(
            (Incoterm.description_es.ilike(f"%{description}%")) |
            (Incoterm.description_en.ilike(f"%{description}%"))
        )
        
    items = query.offset(skip).limit(page_size).all()
    total = query.count()
    return {
        "items": [IncotermDTO.model_validate(obj) for obj in items],
        "total": total,
        "page": page,
        "page_size": page_size,
    }


@router.get(
    "/{key}",
    response_model=IncotermDTO,
    dependencies=[Depends(require_ref_view("ref_incoterms.view"))],
)
async def get_incoterm(
    key: str,
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(get_current_user),
):
    obj = db.query(Incoterm).filter(Incoterm.code == key).first()
    if not obj:
        raise HTTPException(status_code=404, detail="Not found")
    return IncotermDTO.model_validate(obj)


@router.post("/", response_model=IncotermDTO, status_code=201)
async def create_incoterm(
    data: IncotermDTO,
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(has_role("admin")),
):
    obj = Incoterm(**data.model_dump())
    db.add(obj)
    db.commit()
    db.refresh(obj)
    return IncotermDTO.model_validate(obj)


@router.put("/{key}", response_model=IncotermDTO)
async def update_incoterm(
    key: str,
    data: IncotermDTO,
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(has_role("admin")),
):
    obj = db.query(Incoterm).filter(Incoterm.code == key).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 IncotermDTO.model_validate(obj)


@router.delete("/{key}", status_code=204)
async def delete_incoterm(
    key: str,
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(has_role("admin")),
):
    obj = db.query(Incoterm).filter(Incoterm.code == key).first()
    if not obj:
        raise HTTPException(status_code=404, detail="Not found")
    db.delete(obj)
    db.commit()
    return None
