# retoor <retoor@molodetz.nl>

from typing import Optional

from fastapi import HTTPException
from fastapi.responses import JSONResponse

from devplacepy.database import get_setting


def api_enabled() -> bool:
    return get_setting("devrant_api_enabled", "1") == "1"


def ensure_enabled() -> None:
    if not api_enabled():
        raise HTTPException(status_code=404)


def dr_json(payload: dict, status_code: int = 200) -> JSONResponse:
    return JSONResponse(payload, status_code=status_code)


def dr_ok(**fields) -> JSONResponse:
    return dr_json({"success": True, **fields})


def dr_error(message: str, status_code: int = 200, **extra) -> JSONResponse:
    return dr_json({"success": False, "error": message, **extra}, status_code=status_code)


def unauthorized() -> JSONResponse:
    return dr_error("Authentication required.", 401)


def not_found(message: str = "Not found.") -> Optional[JSONResponse]:
    return dr_error(message)
