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

from .dto import AgencyTariffCodeDTO
from .models import AgencyTariffCode
from ..rbac import require_ref_view

router = APIRouter(prefix="/agency-tariff-codes")


@router.get(
    "/",
    response_model=Dict[str, Any],
    dependencies=[Depends(require_ref_view("ref_pedimento_codes.view"))],
)
async def list_agency_tariff_codes(
    page: int = Query(1, ge=1, description="Número de página"),
    page_size: int = Query(50, ge=1, le=1000, description="Tamaño de página"),
    agency: str = Query(None, description="Filtrar por código de agencia"),
    q: str = Query(None, description="Búsqueda general"),
    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(AgencyTariffCode)
    
    if search:
        search_filter = f"%{search}%"
        query = query.filter(
            or_(
                AgencyTariffCode.tariff_flag_code.ilike(search_filter),
                AgencyTariffCode.agency_code.ilike(search_filter),
                AgencyTariffCode.requirement_level.ilike(search_filter),
                AgencyTariffCode.program_code.ilike(search_filter),
                AgencyTariffCode.definition.ilike(search_filter)
            )
        )
    
    if agency:
        query = query.filter(AgencyTariffCode.agency_code == agency)
    
    if q:
        search_term = f"%{q}%"
        query = query.filter(
            or_(
                AgencyTariffCode.tariff_flag_code.ilike(search_term),
                AgencyTariffCode.agency_code.ilike(search_term),
                AgencyTariffCode.program_code.ilike(search_term),
                AgencyTariffCode.definition.ilike(search_term)
            )
        )
    
    items = query.offset(skip).limit(page_size).all()
    total = query.count()
    return {
        "items": [AgencyTariffCodeDTO.model_validate(obj) for obj in items],
        "total": total,
        "page": page,
        "page_size": page_size,
    }


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


@router.post("/", response_model=AgencyTariffCodeDTO, status_code=201)
async def create_agency_tariff_code(
    data: AgencyTariffCodeDTO,
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(has_role("admin")),
):
    obj = AgencyTariffCode(**data.dict())
    db.add(obj)
    db.commit()
    db.refresh(obj)
    return obj


@router.put("/{id}", response_model=AgencyTariffCodeDTO)
async def update_agency_tariff_code(
    id: int,
    data: AgencyTariffCodeDTO,
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(has_role("admin")),
):
    obj = db.query(AgencyTariffCode).filter(AgencyTariffCode.id == id).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("/{id}", status_code=204)
async def delete_agency_tariff_code(
    id: int,
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(has_role("admin")),
):
    obj = db.query(AgencyTariffCode).filter(AgencyTariffCode.id == id).first()
    if not obj:
        raise HTTPException(status_code=404, detail="Not found")
    db.delete(obj)
    db.commit()
    return None
