"""Key management API routes: /api/keys/*"""

from __future__ import annotations

from typing import Any

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

router = APIRouter(prefix="/api/keys", tags=["keys"])


class CreateKeyRequest(BaseModel):
    """Request body for creating a new proxy API key."""

    label: str
    plan: str = "free"
    user_id: str | None = None


@router.post("", status_code=201)
async def create_key(request: Request, body: CreateKeyRequest) -> JSONResponse:
    """Create a new API key with plan metadata."""
    key_store = request.app.state.key_store
    key_id, raw_key = key_store.create_key(label=body.label, plan=body.plan)
    return JSONResponse(
        status_code=201,
        content={
            "key_id": key_id,
            "raw_key": raw_key,
            "label": body.label,
            "plan": body.plan,
        },
    )


@router.get("")
async def list_keys(request: Request) -> dict[str, Any]:
    """List all API keys (metadata only, no raw keys)."""
    key_store = request.app.state.key_store
    return {"keys": key_store.list_keys()}


@router.delete("/{key_id}")
async def revoke_key(request: Request, key_id: str) -> JSONResponse:
    """Revoke an API key by ID."""
    key_store = request.app.state.key_store
    if key_store.revoke_key(key_id):
        return JSONResponse(content={"status": "revoked", "key_id": key_id})
    return JSONResponse(status_code=404, content={"error": "Key not found"})
