"""CORS preflight (OPTIONS) handler for API Gateway Lambda Proxy integrations."""

from __future__ import annotations

from dataclasses import dataclass

from aws_lambda_typing.events import APIGatewayProxyEventV1
from aws_lambda_typing.responses import APIGatewayProxyResponseV1

from ..protocols import ICorsHandler, IRestHandler
from ..rest.cors import request_origin, resolve_allow_origin
from ..rest.responses import DEFAULT_CORS_HEADERS

DEFAULT_ALLOW_HEADERS = "Content-Type,Authorization,X-Correlation-Id"
DEFAULT_ALLOW_METHODS = "GET,POST,PUT,DELETE,OPTIONS"
DEFAULT_MAX_AGE_SECONDS = "86400"


@dataclass(slots=True, frozen=True)
class CorsPreflightRestHandler(IRestHandler[APIGatewayProxyEventV1, APIGatewayProxyResponseV1]):
    """Respond to browser CORS preflight requests."""

    def can_handle(self, event: APIGatewayProxyEventV1) -> bool:
        return event.get("httpMethod") == "OPTIONS"

    def handle(self, event: APIGatewayProxyEventV1) -> APIGatewayProxyResponseV1:
        headers = dict(DEFAULT_CORS_HEADERS)
        headers["Access-Control-Allow-Headers"] = DEFAULT_ALLOW_HEADERS
        headers["Access-Control-Allow-Methods"] = DEFAULT_ALLOW_METHODS
        headers["Access-Control-Max-Age"] = DEFAULT_MAX_AGE_SECONDS
        allow_origin = resolve_allow_origin(request_origin(event.get("headers")))
        if allow_origin:
            headers["Access-Control-Allow-Origin"] = allow_origin

        return {
            "statusCode": 200,
            "headers": headers,
            "multiValueHeaders": {},
            "body": "",
            "isBase64Encoded": False,
        }


@dataclass(slots=True, frozen=True)
class CorsResponseHandler(ICorsHandler):
    """Apply CORS headers to normal Lambda proxy responses."""

    def apply(self, event: APIGatewayProxyEventV1, response: APIGatewayProxyResponseV1) -> APIGatewayProxyResponseV1:
        headers = dict(response.get("headers") or {})
        allow_origin = resolve_allow_origin(request_origin(event.get("headers")))
        if allow_origin:
            headers["Access-Control-Allow-Origin"] = allow_origin
        response["headers"] = headers
        return response


__all__ = ["CorsPreflightRestHandler", "CorsResponseHandler"]

