"""Information fields BFF (normbase `fields`, scoped by org)."""

from __future__ import annotations

import uuid
from typing import Any, Literal

from fastapi import APIRouter, Body, Depends, Query

from aif_platform.server.api.deps import get_normbase_client, get_org_context
from aif_platform.server.infra.upstream import NormbaseClient
from aif_platform.server.models.persistence import PlatformUser
from aif_platform.server.services.access import require_field_in_org

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


def _filter_fields_by_org(data: Any, org_id: uuid.UUID) -> list[Any]:
    if not isinstance(data, list):
        return []
    out: list[Any] = []
    for item in data:
        if not isinstance(item, dict):
            continue
        oid = item.get("org_id")
        if oid is not None and str(oid) == str(org_id):
            out.append(item)
    return out


@router.get("")
async def list_fields(
    ctx: tuple[PlatformUser, uuid.UUID] = Depends(get_org_context),
    nb: NormbaseClient = Depends(get_normbase_client),
    status: Literal["active", "inactive", "archived"] | None = Query(default=None),
):
    _user, org_id = ctx
    raw = await nb.list_fields(status=status)
    return _filter_fields_by_org(raw, org_id)


@router.post("", status_code=201)
async def create_field(
    body: dict[str, Any] = Body(...),
    ctx: tuple[PlatformUser, uuid.UUID] = Depends(get_org_context),
    nb: NormbaseClient = Depends(get_normbase_client),
):
    _user, org_id = ctx
    payload = {**body, "org_id": str(org_id)}
    return await nb.create_field(payload)


@router.patch("/{field_id}")
async def update_field(
    field_id: uuid.UUID,
    body: dict[str, Any] = Body(...),
    ctx: tuple[PlatformUser, uuid.UUID] = Depends(get_org_context),
    nb: NormbaseClient = Depends(get_normbase_client),
):
    _user, org_id = ctx
    await require_field_in_org(nb, field_id=field_id, org_id=org_id)
    payload = {**body, "org_id": str(org_id)}
    return await nb.patch_field(field_id, payload)


@router.delete("/{field_id}")
async def delete_field(
    field_id: uuid.UUID,
    ctx: tuple[PlatformUser, uuid.UUID] = Depends(get_org_context),
    nb: NormbaseClient = Depends(get_normbase_client),
):
    _user, org_id = ctx
    await require_field_in_org(nb, field_id=field_id, org_id=org_id)
    return await nb.delete_field(field_id)
