from typing import cast

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

from iisi_app_core import ApiRequest
from iisi_app_core.handlers.cors import CorsPreflightRestHandler, CorsResponseHandler


def test_cors_preflight_handler_handles_options() -> None:
    handler = CorsPreflightRestHandler()
    event = cast(APIGatewayProxyEventV1, {"httpMethod": "OPTIONS", "headers": {"Origin": "http://localhost:3000"}})

    assert handler.can_handle(event)
    response = handler.handle(event)

    assert response["statusCode"] == 200
    assert response["headers"]["Access-Control-Allow-Methods"] == "GET,POST,PUT,DELETE,OPTIONS"
    assert response["headers"]["Access-Control-Allow-Origin"] == "http://localhost:3000"


def test_cors_response_handler_adds_allow_origin_when_valid() -> None:
    handler = CorsResponseHandler()
    request = ApiRequest.from_event(
        cast(
            APIGatewayProxyEventV1,
            {"httpMethod": "GET", "resource": "/items", "headers": {"Origin": "http://localhost:8080"}},
        )
    )
    response = cast(
        APIGatewayProxyResponseV1,
        {
            "statusCode": 200,
            "headers": {"X-Test": "1"},
            "multiValueHeaders": {},
            "body": "",
            "isBase64Encoded": False,
        },
    )

    output = handler.apply(request, response)

    assert output["headers"]["X-Test"] == "1"
    assert output["headers"]["Access-Control-Allow-Origin"] == "http://localhost:8080"
