"""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/leads")
    assert resp.status_code in (400, 422)


@pytest.mark.asyncio
async def test_lead_tenant_isolation(client):
    create = await client.post(
        "/api/v1/leads",
        json={"title": "Isolated Lead", "owner_user_id": "owner-a"},
        headers=tenant_headers(TENANT_A),
    )
    assert create.status_code == 201, create.text
    lead_id = create.json()["id"]

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

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


@pytest.mark.asyncio
async def test_organization_name_unique_per_tenant(client):
    payload = {"name": "Acme Corp"}
    a1 = await client.post(
        "/api/v1/organizations", json=payload, headers=tenant_headers(TENANT_A)
    )
    a2 = await client.post(
        "/api/v1/organizations", json=payload, headers=tenant_headers(TENANT_A)
    )
    b1 = await client.post(
        "/api/v1/organizations", json=payload, headers=tenant_headers(TENANT_B)
    )
    assert a1.status_code == 201
    assert a2.status_code == 409
    assert b1.status_code == 201
