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 CodePedimentoRegimenDTO
from .models import CodePedimentoRegimen
from ..rbac import require_ref_view

router = APIRouter(prefix="/code-pedimento-regimens")


@router.get(
    "/",
    response_model=Dict[str, Any],
    dependencies=[Depends(require_ref_view("ref_pedimento_regimens.view"))],
)
def list_code_pedimento_regimens(
    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"),
    code: str = Query(None, description="Filter by code"),
    regime: str = Query(None, description="Filter by regime"),
    type: str = Query(None, description="Filter by type"),
    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(CodePedimentoRegimen)
    
    if search:
        search_filter = f"%{search}%"
        query = query.filter(
            or_(
                CodePedimentoRegimen.pedimento_code.ilike(search_filter)
            )
        )

    if code is not None:
        query = query.filter(CodePedimentoRegimen.pedimento_code == code)
    if regime is not None:
        query = query.filter(CodePedimentoRegimen.regimen_code == regime)
    if type is not None:
        query = query.filter(CodePedimentoRegimen.type_code == type)

    items = query.offset(skip).limit(page_size).all()
    total = query.count()
    return {
        "items": [CodePedimentoRegimenDTO.model_validate(obj) for obj in items],
        "total": total,
        "page": page,
        "page_size": page_size,
    }


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


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


@router.put("/{id}", response_model=CodePedimentoRegimenDTO)
def update_code_pedimento_regimen(
    id: int,
    data: CodePedimentoRegimenDTO,
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(has_role("admin")),
):
    obj = db.query(CodePedimentoRegimen).filter(CodePedimentoRegimen.id == id).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 CodePedimentoRegimenDTO.model_validate(obj)


@router.delete("/{id}", status_code=204)
def delete_code_pedimento_regimen(
    id: int,
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(has_role("admin")),
):
    obj = db.query(CodePedimentoRegimen).filter(CodePedimentoRegimen.id == id).first()
    if not obj:
        raise HTTPException(status_code=404, detail="Not found")
    db.delete(obj)
    db.commit()
    return None
