# retoor <retoor@molodetz.nl>

from typing import Optional

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

from devplacepy.database import get_setting
from devplacepy.services.devrant.tokens import resolve_user
from devplacepy.utils.guards import refuse_suspended


def resolve_actor(request: Request, params: dict) -> Optional[dict]:
    user = resolve_user(params)
    if user:
        refuse_suspended(request, user)
    return user


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)
