from tests.conftest import make_app, make_settings, running

FRONTEND = "http://localhost:5173"


def _preflight(origin: str) -> dict[str, str]:
    return {
        "Origin": origin,
        "Access-Control-Request-Method": "POST",
        "Access-Control-Request-Headers": "authorization",
    }


async def test_frontend_origin_may_call_the_api():
    app = make_app(make_settings(cors_allowed_origins=[FRONTEND]))

    async with running(app) as client:
        response = await client.options("/v1/session", headers=_preflight(FRONTEND))

    assert response.status_code == 200
    assert response.headers["access-control-allow-origin"] == FRONTEND
    assert "authorization" in response.headers["access-control-allow-headers"].lower()
    # Bearer tokens only; cookies are never sent cross-origin.
    assert "access-control-allow-credentials" not in response.headers


async def test_other_origins_are_not_allowed():
    app = make_app(make_settings(cors_allowed_origins=[FRONTEND]))

    async with running(app) as client:
        response = await client.options("/v1/session", headers=_preflight("https://evil.test"))

    assert "access-control-allow-origin" not in response.headers


async def test_no_origins_configured_means_no_cross_origin_access():
    async with running(make_app()) as client:
        response = await client.get("/health", headers={"Origin": FRONTEND})

    assert "access-control-allow-origin" not in response.headers


def test_origins_are_read_comma_separated():
    settings = make_settings(cors_allowed_origins="http://a.test, http://b.test")

    assert settings.cors_allowed_origins == ["http://a.test", "http://b.test"]
