"""INDL-59 — `features`/`limits` shape on the public tenant-config lookup.

`GET /api/public/tenants/by-subdomain/{subdomain}` is the tenant-config
endpoint consumed by the admin portal's TenantProvider and by
indelis-frontend. Its `features` dict must be driven by `has_feature()`
(replacing the old inline `plan in (...)` checks), and it must carry a new
`limits.records` field for the Records-usage widget.
"""
from uuid import uuid4

import pytest
from httpx import AsyncClient
from sqlalchemy.ext.asyncio import AsyncSession

from src.apps.tenants.models.account import Account

URL = "/api/public/tenants/by-subdomain/{subdomain}"


async def _make_account(db: AsyncSession, *, plan: str) -> Account:
    uid = uuid4().hex[:8]
    acc = Account(
        organization_name=f"Plan Gate Cemetery {uid}",
        subdomain=f"plangate-public-{plan}-{uid}",
        contact_email=f"admin-{uid}@plangate.test",
        plan=plan,
        status="active",
    )
    db.add(acc)
    await db.flush()
    return acc


@pytest.mark.asyncio
async def test_starter_features_and_limits_shape(client: AsyncClient, db_session: AsyncSession):
    acc = await _make_account(db_session, plan="starter")

    resp = await client.get(URL.format(subdomain=acc.subdomain))
    assert resp.status_code == 200
    data = resp.json()["data"]

    assert data["features"]["planType"] == "starter"
    assert data["features"]["aiSearch"] is False
    assert data["features"]["aiRecordExtraction"] is False
    assert data["features"]["aiBiographyWriter"] is False
    assert data["limits"] == {"records": 5000}


@pytest.mark.asyncio
async def test_professional_features_and_limits_shape(client: AsyncClient, db_session: AsyncSession):
    acc = await _make_account(db_session, plan="professional")

    resp = await client.get(URL.format(subdomain=acc.subdomain))
    assert resp.status_code == 200
    data = resp.json()["data"]

    assert data["features"]["planType"] == "professional"
    assert data["features"]["aiSearch"] is True
    assert data["features"]["aiRecordExtraction"] is True
    assert data["features"]["aiBiographyWriter"] is True
    assert data["limits"] == {"records": 25000}


@pytest.mark.asyncio
async def test_enterprise_features_and_limits_shape(client: AsyncClient, db_session: AsyncSession):
    acc = await _make_account(db_session, plan="enterprise")

    resp = await client.get(URL.format(subdomain=acc.subdomain))
    assert resp.status_code == 200
    data = resp.json()["data"]

    assert data["features"]["planType"] == "enterprise"
    assert data["features"]["aiSearch"] is True
    assert data["features"]["aiRecordExtraction"] is True
    assert data["features"]["aiBiographyWriter"] is True
    # Unlimited — None, not a large integer sentinel.
    assert data["limits"] == {"records": None}
