# retoor <retoor@molodetz.nl>

from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse

from devplacepy.schemas import DbRowOut, DbRowsOut
from devplacepy.services.dbapi import crud
from devplacepy.services.dbapi.crud import DbApiError

from ._shared import (
    assert_table,
    error,
    parse_filters,
    require_dbapi_caller,
)

router = APIRouter()


@router.get("/{table}")
async def dbapi_list(
    request: Request,
    table: str,
    limit: int = 25,
    before: str = None,
    search: str = "",
    include_deleted: bool = False,
):
    require_dbapi_caller(request)
    assert_table(table)
    filters, comparisons = parse_filters(request)
    rows, next_cursor = crud.list_rows(
        table,
        filters=filters,
        comparisons=comparisons,
        search=search,
        before=before,
        limit=limit,
        include_deleted=include_deleted,
    )
    return JSONResponse(
        DbRowsOut(
            table=table, rows=rows, count=len(rows), next_cursor=next_cursor
        ).model_dump(mode="json")
    )


@router.get("/{table}/{key}/{value}")
async def dbapi_get(request: Request, table: str, key: str, value: str):
    require_dbapi_caller(request)
    assert_table(table)
    try:
        row = crud.get_row(table, key, value)
    except DbApiError as exc:
        return error(400, str(exc))
    if row is None:
        return error(404, "Row not found")
    return JSONResponse(DbRowOut(table=table, row=row).model_dump(mode="json"))
