"""API key authentication middleware.

AUTO-GENERATED BY PRISM - DO NOT EDIT
FastAPI dependencies for API key authentication.
"""

from __future__ import annotations

from typing import Annotated

from fastapi import Depends, HTTPException, Request, status
{% if scheme %}
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
{% endif %}

from {{ project_name }}.auth.api_key_service import api_key_service, APIKeyError

{% if scheme %}
# Use Bearer token scheme
security = HTTPBearer(auto_error=False)


async def get_api_key(
    request: Request,
    credentials: HTTPAuthorizationCredentials | None = Depends(security),
) -> str:
    """Extract and verify API key from request.

    Supports both:
    - {{ header }}: {{ scheme }} <key>
    - {{ header }}: <key> (fallback)

    Args:
        request: FastAPI request object
        credentials: HTTP Bearer credentials (if present)

    Returns:
        Verified API key

    Raises:
        HTTPException: If API key is missing or invalid (401)
    """
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Invalid or missing API key",
        headers={"WWW-Authenticate": "{{ scheme }}"},
    )

    api_key: str | None = None

    # Try to get from Bearer credentials first
    if credentials:
        api_key = credentials.credentials
    else:
        # Fallback: check raw header value
        header_value = request.headers.get("{{ header }}")
        if header_value:
            # Strip scheme prefix if present
            if header_value.startswith("{{ scheme }} "):
                api_key = header_value[len("{{ scheme }} "):]
            else:
                api_key = header_value

    if not api_key:
        raise credentials_exception

    try:
        api_key_service.require_key(api_key)
    except APIKeyError:
        raise credentials_exception

    return api_key
{% else %}
async def get_api_key(request: Request) -> str:
    """Extract and verify API key from {{ header }} header.

    Args:
        request: FastAPI request object

    Returns:
        Verified API key

    Raises:
        HTTPException: If API key is missing or invalid (401)
    """
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Invalid or missing API key",
    )

    api_key = request.headers.get("{{ header }}")

    if not api_key:
        raise credentials_exception

    try:
        api_key_service.require_key(api_key)
    except APIKeyError:
        raise credentials_exception

    return api_key
{% endif %}


def require_api_key():
    """Dependency for protecting routes with API key authentication.

    Usage:
        @router.get("/protected", dependencies=[Depends(require_api_key())])
        async def protected_route():
            ...

    Or inject the key:
        @router.get("/protected")
        async def protected_route(api_key: str = Depends(require_api_key())):
            ...
    """
    return Depends(get_api_key)


# Type alias for convenience
APIKey = Annotated[str, Depends(get_api_key)]
