from __future__ import annotations

from fastapi import Request
from fastapi.responses import JSONResponse
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.types import ASGIApp


class APIKeyMiddleware(BaseHTTPMiddleware):
    """Middleware responsável por validar a header ``x-api-key`` quando configurado."""

    def __init__(self, app: ASGIApp, api_key: str | None) -> None:
        super().__init__(app)
        self._api_key = (api_key or "").strip()

    async def dispatch(self, request: Request, call_next):  # type: ignore[override]
        if not self._api_key:
            return await call_next(request)

        provided_key = request.headers.get("x-api-key")
        if provided_key != self._api_key:
            return JSONResponse(
                status_code=401,
                content={"detail": "Invalid or missing API key"},
            )

        return await call_next(request)
