
from typing import Any, Dict, Optional

from core.database import get_core_db
from core.security import get_current_user
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy import or_
from sqlalchemy.orm import Session

from .dto import SectorDTO
from .models import Sector

router = APIRouter(prefix="/sectors")


@router.get("/", response_model=Dict[str, Any])
def list_sectors(
    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"),
    search: Optional[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(Sector)
    
    if search:
        search_filter = or_(
            Sector.key.ilike(f"%{search}%"),
            Sector.description.ilike(f"%{search}%")
        )
        query = query.filter(search_filter)
        
    total = query.count()
    # Add deterministic sort order
    query = query.order_by(Sector.key)
    items = query.offset(skip).limit(page_size).all()
    
    return {
        "items": [SectorDTO.model_validate(obj) for obj in items],
        "total": total,
        "page": page,
        "page_size": page_size,
    }


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