"""Information fields management API."""
from __future__ import annotations

from typing import List, Optional, Literal
from uuid import UUID

from fastapi import APIRouter, Depends, Query, status
from sqlalchemy.ext.asyncio import AsyncSession

from normbase.db.connection import get_db
from normbase.schemas import FieldCreate, FieldResponse, FieldUpdate
from normbase.services.field_service import FieldService


router = APIRouter(tags=["fields"])
_field_service = FieldService()


@router.get("/fields", response_model=List[FieldResponse])
async def list_fields(
    status: Optional[Literal["active", "inactive", "archived"]] = Query(
        default=None,
        description="Filter by field status",
    ),
    db: AsyncSession = Depends(get_db),
):
    rows = await _field_service.list_fields(db, status_filter=status)
    return [FieldResponse.model_validate(row) for row in rows]


@router.post("/fields", response_model=FieldResponse, status_code=status.HTTP_201_CREATED)
async def create_field(payload: FieldCreate, db: AsyncSession = Depends(get_db)):
    item = await _field_service.create_field(
        db,
        name=payload.name,
        description=(payload.description or None),
        org_id=payload.org_id,
        status_value=payload.status,
    )
    return FieldResponse.model_validate(item)


@router.patch("/fields/{field_id}", response_model=FieldResponse)
async def update_field(field_id: UUID, payload: FieldUpdate, db: AsyncSession = Depends(get_db)):
    item = await _field_service.update_field(
        db,
        field_id=field_id,
        name=payload.name,
        description=payload.description,
        org_id=payload.org_id,
        status_value=payload.status,
    )
    return FieldResponse.model_validate(item)


@router.delete("/fields/{field_id}", response_model=FieldResponse)
async def soft_delete_field(field_id: UUID, db: AsyncSession = Depends(get_db)):
    item = await _field_service.soft_delete_field(db, field_id=field_id)
    return FieldResponse.model_validate(item)
