from collections.abc import Callable

from django.http import HttpRequest, HttpResponse


class CrossOriginEmbedderPolicyMiddleware:
    """
    This middleware adds COEP (Cross-Origin-Embedder-Policy) header to all responses.

    We set the value for this header to "require-corp" to enforce that the resources can only be
    allowed to load if they come from the same origin, or if the resource is explicitly marked
    as loadable from another origin.

    .. seealso: `<https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Embedder-Policy>`_
    """

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

    def __call__(self, request: HttpRequest) -> HttpResponse:
        """Add COEP header to the response."""
        response = self.get_response(request)
        response["Cross-Origin-Embedder-Policy"] = "require-corp"
        return response
