# retoor <retoor@molodetz.nl>

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

from devplacepy.database import get_table
from devplacepy.schemas import DbSchemaOut, DbTableListOut
from devplacepy.services.dbapi import crud, policy

from ._shared import assert_table, require_dbapi_caller

router = APIRouter()


@router.get("/tables")
async def dbapi_tables(request: Request):
    require_dbapi_caller(request)
    tables = []
    for name in policy.allowed_tables():
        tables.append(
            {
                "name": name,
                "row_count": get_table(name).count(),
                "soft_delete": policy.soft_delete_aware(name),
            }
        )
    return JSONResponse(
        DbTableListOut(tables=tables, count=len(tables)).model_dump(mode="json")
    )


@router.get("/{table}/schema")
async def dbapi_schema(request: Request, table: str):
    require_dbapi_caller(request)
    assert_table(table)
    return JSONResponse(DbSchemaOut(**crud.schema(table)).model_dump(mode="json"))
