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

from app.core.security.session_auth import SESSION_USER_ID_KEY


class SecurityHeadersMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        # Capture authentication state before the route runs. Logout clears the
        # session during the request, but its response must still be non-cacheable.
        was_authenticated = bool(request.session.get(SESSION_USER_ID_KEY))

        resp = await call_next(request)
        resp.headers["X-Content-Type-Options"] = "nosniff"
        resp.headers["X-Frame-Options"] = "DENY"
        resp.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
        resp.headers["Permissions-Policy"] = "geolocation=(), microphone=(), camera=()"

        # CSP: allow Tailwind CDN only
        resp.headers["Content-Security-Policy"] = (
            "default-src 'self'; "
            "style-src 'self' 'unsafe-inline' https://cdn.tailwindcss.com; "
            "script-src 'self' 'unsafe-inline' https://cdn.tailwindcss.com; "
            "img-src 'self' data:; "
            "connect-src 'self'; "
            "frame-ancestors 'none';"
        )

        # Authenticated ERP pages contain client, PAN, document, billing and
        # engagement data. Prevent browsers and intermediary caches from storing
        # them, including responses generated immediately before logout.
        is_authenticated = bool(request.session.get(SESSION_USER_ID_KEY))
        if was_authenticated or is_authenticated:
            resp.headers["Cache-Control"] = (
                "no-store, no-cache, must-revalidate, private, max-age=0"
            )
            resp.headers["Pragma"] = "no-cache"
            resp.headers["Expires"] = "0"

        return resp
