"""API endpoints for API key management."""

from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.routing import Route

from fenliu.database import get_db
from fenliu.services.api_key import delete_api_key
from fenliu.services.api_key import generate_api_key
from fenliu.services.api_key import get_api_key
from fenliu.services.api_key import set_api_key


async def get_api_key_status(request: Request) -> JSONResponse:  # noqa: ARG001
    """Get current API key status (without exposing the full key).

    Returns whether an API key is currently set.
    """
    with get_db() as db:
        key = get_api_key(db)
        has_key = key is not None
        return JSONResponse(
            {
                "api_key_set": has_key,
                "message": "API key is set" if has_key else "No API key configured",
            }
        )


async def generate_new_api_key(request: Request) -> JSONResponse:  # noqa: ARG001
    """Generate a new API key, overwriting any existing key.

    Returns the newly generated API key (only time it's visible).
    """
    try:
        new_key = generate_api_key()
        set_api_key(new_key)
        return JSONResponse(
            {
                "success": True,
                "api_key": new_key,
                "message": "API key generated successfully. Store it safely - you won't see it again!",
            },
            status_code=201,
        )
    except Exception as e:
        return JSONResponse(
            {
                "success": False,
                "error": str(e),
            },
            status_code=500,
        )


async def revoke_api_key(request: Request) -> JSONResponse:  # noqa: ARG001
    """Revoke (delete) the current API key.

    Called from the settings UI where user context is implicit.
    """
    try:
        delete_api_key()
        return JSONResponse(
            {
                "success": True,
                "message": "API key revoked successfully",
            }
        )
    except Exception as e:
        return JSONResponse(
            {
                "success": False,
                "error": str(e),
            },
            status_code=500,
        )


# Create API key routes
api_key_routes = [
    Route("/status", get_api_key_status, methods=["GET"]),
    Route("/generate", generate_new_api_key, methods=["POST"]),
    Route("/revoke", revoke_api_key, methods=["POST"]),
]
