"""CORS handler compatibility helpers."""

from dataclasses import dataclass, field

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

from ..dispatch.api_gateway import DefaultCorsPolicy
from ..dispatch.contracts import ApiRoute
from ..dispatch.models import ApiRequest


@dataclass(slots=True, frozen=True)
class CorsPreflightRestHandler:
    """Compatibility wrapper for preflight handling."""

    route: ApiRoute = field(default_factory=lambda: ApiRoute(method="OPTIONS", resource="*"))
    cors_policy: DefaultCorsPolicy = field(default_factory=DefaultCorsPolicy)

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

    def handle(self, event: APIGatewayProxyEventV1) -> APIGatewayProxyResponseV1:
        request = ApiRequest.from_event(event)
        response = self.cors_policy.preflight(request)
        if response is None:
            raise RuntimeError("CorsPreflightRestHandler can only handle OPTIONS requests.")
        return response


@dataclass(slots=True, frozen=True)
class CorsResponseHandler(DefaultCorsPolicy):
    """Compatibility alias for the default CORS policy."""


__all__ = ["CorsPreflightRestHandler", "CorsResponseHandler"]
