from __future__ import annotations

from iisi_app_core.handlers.cors import CorsPreflightRestHandler, CorsResponseHandler


def test_cors_preflight_handler_handles_options() -> None:
    handler = CorsPreflightRestHandler()
    event = {"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()
    event = {"headers": {"Origin": "http://localhost:8080"}}
    response = {
        "statusCode": 200,
        "headers": {"X-Test": "1"},
        "multiValueHeaders": {},
        "body": "",
        "isBase64Encoded": False,
    }

    output = handler.apply(event, response)

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