"""Tenant isolation API tests."""
from __future__ import annotations

import pytest

from app.tests.conftest import TENANT_A, TENANT_B, tenant_headers


@pytest.mark.asyncio
async def test_tenant_required(client):
    resp = await client.get("/api/v1/programs")
    assert resp.status_code in (400, 422)


@pytest.mark.asyncio
async def test_program_tenant_isolation(client):
    create = await client.post(
        "/api/v1/programs",
        json={"code": "GOLD", "name": "Gold Program"},
        headers=tenant_headers(TENANT_A),
    )
    assert create.status_code == 201, create.text
    program_id = create.json()["id"]

    list_b = await client.get("/api/v1/programs", headers=tenant_headers(TENANT_B))
    assert list_b.status_code == 200
    assert all(item["id"] != program_id for item in list_b.json())

    get_b = await client.get(
        f"/api/v1/programs/{program_id}", headers=tenant_headers(TENANT_B)
    )
    assert get_b.status_code == 404


@pytest.mark.asyncio
async def test_program_code_unique_per_tenant(client):
    payload = {"code": "VIP", "name": "VIP Club"}
    a1 = await client.post(
        "/api/v1/programs", json=payload, headers=tenant_headers(TENANT_A)
    )
    a2 = await client.post(
        "/api/v1/programs", json=payload, headers=tenant_headers(TENANT_A)
    )
    b1 = await client.post(
        "/api/v1/programs", json=payload, headers=tenant_headers(TENANT_B)
    )
    assert a1.status_code == 201
    assert a2.status_code == 409
    assert b1.status_code == 201
