"""Phase 10.4 — Pricing, Capabilities & Bundles tests."""
from __future__ import annotations

import pytest

from app.events.publisher import get_event_publisher
from app.tests.conftest import TENANT_A, tenant_headers


async def _org(client):
    resp = await client.post(
        "/api/v1/organizations",
        headers=tenant_headers(TENANT_A),
        json={"code": "ORG_P104", "name": "Pricing Org", "status": "active"},
    )
    assert resp.status_code == 201
    return resp.json()


@pytest.mark.asyncio
async def test_pricing_capability_bundle_flow(client):
    org = await _org(client)

    rule = await client.post(
        "/api/v1/pricing-rules",
        headers=tenant_headers(TENANT_A),
        json={
            "organization_id": org["id"],
            "code": "PR1",
            "name": "Base Delivery",
            "base_amount": "50000",
            "currency_code": "IRR",
        },
    )
    assert rule.status_code == 201, rule.text
    rid = rule.json()["id"]

    cap = await client.post(
        "/api/v1/capabilities",
        headers=tenant_headers(TENANT_A),
        json={"code": "COLD", "name": "Cold Chain"},
    )
    assert cap.status_code == 201

    bundle = await client.post(
        "/api/v1/bundles",
        headers=tenant_headers(TENANT_A),
        json={
            "code": "BND1",
            "name": "Cold Bundle",
            "capability_codes": ["COLD"],
            "pricing_rule_id": rid,
        },
    )
    assert bundle.status_code == 201, bundle.text

    listed = await client.get(
        "/api/v1/pricing-rules",
        headers=tenant_headers(TENANT_A),
    )
    assert listed.status_code == 200
    assert listed.json()["total"] >= 1

    events = {e.event_type for e in get_event_publisher().published}
    assert "delivery.pricing_rule.created" in events
    assert "delivery.capability.created" in events
    assert "delivery.bundle.created" in events
