from __future__ import annotations

from fastapi import FastAPI, Request, Response


def install_security_headers(application: FastAPI) -> None:
    @application.middleware("http")
    async def security_headers(request: Request, call_next) -> Response:
        response = await call_next(request)
        response.headers["X-Content-Type-Options"] = "nosniff"
        response.headers["Referrer-Policy"] = "same-origin"
        response.headers["X-Frame-Options"] = "DENY"
        response.headers["Permissions-Policy"] = "camera=(), microphone=(), geolocation=()"
        if request.app.state.settings.environment == "production":
            response.headers["Content-Security-Policy"] = (
                "default-src 'self'; base-uri 'self'; frame-ancestors 'none'; "
                "form-action 'self'; img-src 'self' data:; font-src 'self'; "
                "style-src 'self' 'unsafe-inline'; script-src 'self'; connect-src 'self'"
            )
            if request.url.scheme == "https":
                response.headers["Strict-Transport-Security"] = (
                    "max-age=31536000; includeSubDomains"
                )
        return response
