"""Reference collections that user documents point at.

Needed to render or validate a user's department / team / country / state.
"""

from typing import Annotated, Any, Optional

from fastapi import APIRouter, Query

from ..crud import to_object_id
from ..db import get_db

router = APIRouter(prefix="/lookups", tags=["lookups"])


def _clean(doc: dict[str, Any]) -> dict[str, Any]:
    return {k: (str(v) if k == "_id" or k.endswith("_id") else v) for k, v in doc.items()}


@router.get("/departments", summary="Departments referenced by users.department")
async def departments():
    rows = await get_db()["departments"].find().sort("dept_id", 1).to_list(length=None)
    return [_clean(r) for r in rows]


@router.get("/teams", summary="Teams referenced by users.team_id")
async def teams():
    rows = await get_db()["teams"].find().sort("team", 1).to_list(length=None)
    return [_clean(r) for r in rows]


@router.get("/countries", summary="Countries referenced by users.country")
async def countries():
    rows = (
        await get_db()["countries"]
        .find({}, {"_id": 1, "code": 1, "name": 1, "status": 1})
        .sort("name", 1)
        .to_list(length=None)
    )
    return [_clean(r) for r in rows]


@router.get("/states", summary="States referenced by users.state")
async def states(
    country_id: Annotated[Optional[str], Query(description="Filter by country ObjectId")] = None,
):
    query: dict[str, Any] = {}
    if country_id:
        oid = to_object_id(country_id)
        query["country_id"] = oid if oid is not None else country_id

    rows = await get_db()["states"].find(query).sort("state_name", 1).to_list(length=None)
    return [_clean(r) for r in rows]
