"""Privacy headers and cookie-origin policy without database access."""

import pytest
from httpx import ASGITransport, AsyncClient
from starlette.responses import JSONResponse

from app.config import settings
from app.core.http_middleware import HTTPPolicyMiddleware


async def endpoint(scope, receive, send):
    await JSONResponse({"ok": True})(scope, receive, send)


@pytest.mark.asyncio
async def test_policy_headers_and_cookie_origins(monkeypatch):
    monkeypatch.setattr(settings, "APP_ENV", "production")
    monkeypatch.setattr(settings, "APP_ALLOWED_ORIGINS", ["https://lab.example"])
    async with AsyncClient(
        transport=ASGITransport(app=HTTPPolicyMiddleware(endpoint)), base_url="https://api.example"
    ) as client:
        allowed = await client.post(
            "/api/v1/example", headers={"Cookie": "access_token=example", "Origin": "https://lab.example"}
        )
        assert allowed.status_code == 200
        assert allowed.headers["cache-control"] == "no-store"
        assert allowed.headers["x-content-type-options"] == "nosniff"
        assert allowed.headers["referrer-policy"] == "no-referrer"
        assert "app;dur=" in allowed.headers["server-timing"]
        assert len(allowed.headers["x-request-id"]) == 36
        for origin in ["https://evil.example", None]:
            headers = {"Cookie": "access_token=example"}
            if origin:
                headers["Origin"] = origin
            assert (await client.post("/api/v1/example", headers=headers)).status_code == 403
        assert (
            await client.post("/api/v1/example", headers={"Authorization": "Bearer example"})
        ).status_code == 200
