"""تست‌های قابلیت‌ها و بررسی دسترسی (Entitlement)."""
from __future__ import annotations


async def _setup_tenant_with_plan(client, *, slug, feature_key, attach=True, active=True):
    """ساخت tenant، پلن، قابلیت، اتصال و اشتراک برای سناریوی تست."""
    tenant_id = (
        await client.post("/api/v1/tenants", json={"name": "T", "slug": slug})
    ).json()["id"]

    plan_id = (
        await client.post(
            "/api/v1/plans", json={"code": f"plan-{slug}", "name": "Plan"}
        )
    ).json()["id"]

    feature_id = (
        await client.post(
            "/api/v1/features",
            json={
                "feature_key": feature_key,
                "name": "Feature",
                "service_key": feature_key.split(".")[0],
            },
        )
    ).json()["id"]

    if attach:
        await client.post(
            f"/api/v1/plans/{plan_id}/features",
            json={"feature_id": feature_id, "is_enabled": True},
        )

    await client.post(
        f"/api/v1/tenants/{tenant_id}/subscription",
        json={"plan_id": plan_id, "status": "active" if active else "expired"},
    )
    return tenant_id


async def test_create_feature(client):
    resp = await client.post(
        "/api/v1/features",
        json={
            "feature_key": "accounting.invoice.create",
            "name": "ساخت فاکتور",
            "service_key": "accounting",
        },
    )
    assert resp.status_code == 201
    assert resp.json()["feature_key"] == "accounting.invoice.create"


async def test_feature_key_unique(client):
    payload = {
        "feature_key": "crm.lead.create",
        "name": "Lead",
        "service_key": "crm",
    }
    first = await client.post("/api/v1/features", json=payload)
    assert first.status_code == 201
    second = await client.post("/api/v1/features", json=payload)
    assert second.status_code == 409


async def test_check_feature_access_granted(client):
    tenant_id = await _setup_tenant_with_plan(
        client, slug="grant", feature_key="ecommerce.product.create"
    )
    resp = await client.post(
        f"/api/v1/tenants/{tenant_id}/features/check",
        json={"feature_key": "ecommerce.product.create"},
    )
    assert resp.status_code == 200
    body = resp.json()
    assert body["has_access"] is True
    assert body["reason"] == "plan_enabled"


async def test_check_feature_access_denied_when_not_in_plan(client):
    tenant_id = await _setup_tenant_with_plan(
        client,
        slug="denyplan",
        feature_key="live_chat.widget.enable",
        attach=False,
    )
    resp = await client.post(
        f"/api/v1/tenants/{tenant_id}/features/check",
        json={"feature_key": "live_chat.widget.enable"},
    )
    assert resp.status_code == 200
    assert resp.json()["has_access"] is False


async def test_check_feature_access_denied_when_subscription_inactive(client):
    tenant_id = await _setup_tenant_with_plan(
        client,
        slug="expired",
        feature_key="ai_assistant.chat.reply",
        active=False,
    )
    resp = await client.post(
        f"/api/v1/tenants/{tenant_id}/features/check",
        json={"feature_key": "ai_assistant.chat.reply"},
    )
    assert resp.status_code == 200
    assert resp.json()["has_access"] is False
