"""Authentication routes — token issuance and API key management."""

from __future__ import annotations

from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel

from src.api.auth import (
    AuthUser,
    create_access_token,
    create_api_key,
    get_current_user,
    require_admin,
    revoke_api_key,
)

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


# ---------------------------------------------------------------------------
# Request / response models
# ---------------------------------------------------------------------------


class TokenRequest(BaseModel):
    user_id: str
    password: str


class TokenResponse(BaseModel):
    access_token: str
    token_type: str = "bearer"
    user_id: str


class APIKeyRequest(BaseModel):
    label: str = "default"


class APIKeyResponse(BaseModel):
    api_key: str
    label: str
    warning: str = "Store this key securely — it cannot be retrieved again."


# ---------------------------------------------------------------------------
# Routes
# ---------------------------------------------------------------------------


@router.post("/token", response_model=TokenResponse)
async def login(body: TokenRequest):
    """Issue a JWT access token.

    In the current implementation, any user_id + password "penbot"
    combination works. Replace with a real user store for production.
    """
    if body.password != "penbot":
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid credentials",
        )

    role = "admin" if body.user_id == "admin" else "user"
    token = create_access_token(body.user_id, role=role)

    return TokenResponse(access_token=token, user_id=body.user_id)


@router.get("/me")
async def whoami(user: AuthUser = Depends(get_current_user)):
    """Return the currently authenticated user."""
    return {
        "user_id": user.user_id,
        "role": user.role,
        "auth_method": user.via,
    }


@router.post("/api-keys", response_model=APIKeyResponse)
async def generate_api_key(
    body: APIKeyRequest,
    user: AuthUser = Depends(get_current_user),
):
    """Generate a new API key for the current user."""
    raw = create_api_key(user.user_id, label=body.label)
    return APIKeyResponse(api_key=raw, label=body.label)


@router.delete("/api-keys/{raw_key}")
async def delete_api_key(
    raw_key: str,
    user: AuthUser = Depends(require_admin),
):
    """Revoke an API key (admin only)."""
    if revoke_api_key(raw_key):
        return {"status": "revoked"}
    raise HTTPException(status_code=404, detail="API key not found")
