"""Middleware that applies a hardened set of security headers."""

from __future__ import annotations

from typing import Mapping

from fastapi import Request, Response
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.types import ASGIApp


_DEFAULT_HEADERS: dict[str, str] = {
    "Strict-Transport-Security": "max-age=63072000; includeSubDomains; preload",
    "X-Content-Type-Options": "nosniff",
    "X-Frame-Options": "DENY",
    "Referrer-Policy": "no-referrer",
    "Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'",
    "Permissions-Policy": "geolocation=(), microphone=(), camera=()",
}


class SecurityHeadersMiddleware(BaseHTTPMiddleware):
    """Append a curated set of security headers to every response."""

    def __init__(self, app: ASGIApp, headers: Mapping[str, str] | None = None) -> None:
        super().__init__(app)
        self.headers = dict(_DEFAULT_HEADERS)
        if headers:
            self.headers.update(headers)

    async def dispatch(self, request: Request, call_next):
        response: Response = await call_next(request)
        for key, value in self.headers.items():
            response.headers.setdefault(key, value)
        return response
