from collections.abc import Callable

from django.http import HttpRequest, HttpResponse


class CrossOriginResourcePolicyMiddleware:
    """
    This middleware adds CORP (Cross-Origin-Resource-Policy) header to all responses.

    We currently set this value to "cross-origin" as the portal relies on some external CDNs,
    which would otherwise be blocked by more restrictive values, like "same-origin" or "same-site".
    This will make browsers act the same way as if this server didn't send this header at all.
    However, it is a good practice to explicitly add this header, to make it obvious that we know
    about it's use and that we are intentionally allowing cross-origin requests.

    .. seealso: `<https://resourcepolicy.fyi/>`_
    """

    def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]):
        self.get_response = get_response

    def __call__(self, request: HttpRequest) -> HttpResponse:
        """Add CORP header to the response."""
        response = self.get_response(request)
        response["Cross-Origin-Resource-Policy"] = "cross-origin"
        return response
