"""Middleware to require API key authentication."""

from fastapi import Request

from hezor_common.transfer.middlewares.constants import ERR_RES_HEADER_API_KEY


class RequireAPIKey:
    """Dependency factory for API key authentication with configurable realm.

    This class can be instantiated with a custom realm parameter or used as
    a default instance for backward compatibility.

    Parameters
    ----------
    realm : str, optional
        The authentication realm for WWW-Authenticate header
        (default: "Access to the protected resource")

    Examples
    --------
    >>> from fastapi import Depends
    >>> # Using default instance (backward compatible)
    >>> @app.get("/protected")
    >>> async def protected_route(api_key: str = Depends(require_api_key)):
    ...     return {"message": "Access granted"}
    >>> # Using custom realm
    >>> @app.get("/admin")
    >>> async def admin_route(api_key: str = Depends(RequireAPIKey("Admin area"))):
    ...     return {"message": "Admin access"}
    """

    def __init__(self, realm: str = "Access to the protected resource"):
        """Initialize the API key dependency with custom realm.

        Parameters
        ----------
        realm : str, optional
            The authentication realm for WWW-Authenticate header
        """
        self.realm = realm

    def __call__(self, request: Request) -> str:
        """Dependency to extract and require valid API key.

        Parameters
        ----------
        request : Request
            FastAPI request object

        Returns
        -------
        str
            Validated API key

        Raises
        ------
        HTTPException
            If API key is missing or invalid
        """
        from fastapi import HTTPException

        if hasattr(request.state, "api_key_error") and request.state.api_key_error:
            raise HTTPException(
                status_code=401,
                detail=request.state.api_key_error,
                headers=ERR_RES_HEADER_API_KEY(realm=self.realm),
            )

        if not hasattr(request.state, "api_key") or request.state.api_key is None:
            raise HTTPException(
                status_code=401,
                detail="API key required",
                headers=ERR_RES_HEADER_API_KEY(realm=self.realm),
            )

        return request.state.api_key


# Default instance for backward compatibility
require_api_key = RequireAPIKey()
