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 .dto import CustomsSectionDTO
from .models import CustomsSection

router = APIRouter(prefix="/customs-sections")


@router.get("/", response_model=Dict[str, Any])
def list_customs_sections(
    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"),
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(get_current_user),
):
    skip = (page - 1) * page_size
    query = db.query(CustomsSection)
    items = query.offset(skip).limit(page_size).all()
    total = query.count()
    return {
        "items": [CustomsSectionDTO.model_validate(obj) for obj in items],
        "total": total,
        "page": page,
        "page_size": page_size,
    }


@router.get("/{customs_code}", response_model=CustomsSectionDTO)
def get_customs_section(
    customs_code: str,
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(get_current_user),
):
    obj = (
        db.query(CustomsSection)
        .filter(CustomsSection.customs_code == customs_code)
        .first()
    )
    if not obj:
        raise HTTPException(status_code=404, detail="Not found")
    return obj


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


@router.put("/{customs_code}", response_model=CustomsSectionDTO)
def update_customs_section(
    customs_code: str,
    data: CustomsSectionDTO,
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(has_role("admin")),
):
    obj = (
        db.query(CustomsSection)
        .filter(CustomsSection.customs_code == customs_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("/{customs_code}", status_code=204)
def delete_customs_section(
    customs_code: str,
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(has_role("admin")),
):
    obj = (
        db.query(CustomsSection)
        .filter(CustomsSection.customs_code == customs_code)
        .first()
    )
    if not obj:
        raise HTTPException(status_code=404, detail="Not found")
    db.delete(obj)
    db.commit()
    return None
