"""Dynamic CORS middleware that checks the in-memory domain whitelist.

Replaces FastAPI's static ``CORSMiddleware`` so origins can be
added/removed at runtime without restarting the server.
"""

from __future__ import annotations

from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import Response

from .domains import is_origin_allowed


class DynamicCORSMiddleware(BaseHTTPMiddleware):
    """CORS middleware that checks ``domains.is_origin_allowed()`` per request."""

    async def dispatch(self, request: Request, call_next):
        origin = request.headers.get("origin")

        # --- Preflight (OPTIONS) ---
        if request.method == "OPTIONS" and origin:
            response = Response(status_code=200)
            if is_origin_allowed(origin):
                response.headers["Access-Control-Allow-Origin"] = origin
                response.headers["Access-Control-Allow-Credentials"] = "true"
                response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS"
                response.headers["Access-Control-Allow-Headers"] = (
                    "Authorization, Content-Type, X-Requested-With, X-Internal-Token"
                )
                response.headers["Access-Control-Max-Age"] = "600"
            return response

        # --- Normal request ---
        response = await call_next(request)

        if origin and is_origin_allowed(origin):
            response.headers["Access-Control-Allow-Origin"] = origin
            response.headers["Access-Control-Allow-Credentials"] = "true"
            response.headers["Vary"] = "Origin"

        return response
