"""Phase 10.8 — Settlement tests (AccountingProvider refs only)."""
from __future__ import annotations

import pytest

from app.core.database import Base
from app.events.publisher import get_event_publisher
import app.models  # noqa: F401
from app.tests.conftest import TENANT_A, tenant_headers


def test_no_journal_entry_table_in_delivery_db():
    names = set(Base.metadata.tables.keys())
    forbidden = {
        "journal_entries",
        "journal_entry",
        "accounting_journal_entries",
        "accounting_journals",
    }
    assert names.isdisjoint(forbidden)
    for name in names:
        assert "journal" not in name.lower()


@pytest.mark.asyncio
async def test_settlement_intent_via_accounting_provider_ref(client):
    org = await client.post(
        "/api/v1/organizations",
        headers=tenant_headers(TENANT_A),
        json={"code": "ORG_S108", "name": "Settlement Org", "status": "active"},
    )
    assert org.status_code == 201
    org_id = org.json()["id"]

    intent = await client.post(
        "/api/v1/settlements",
        headers=tenant_headers(TENANT_A),
        json={
            "organization_id": org_id,
            "code": "SET1",
            "total_amount": "120000",
            "currency_code": "IRR",
        },
    )
    assert intent.status_code == 201, intent.text
    iid = intent.json()["id"]
    version = intent.json()["version"]
    assert intent.json()["external_settlement_ref"] is None

    line = await client.post(
        f"/api/v1/settlements/{iid}/lines",
        headers=tenant_headers(TENANT_A),
        json={"kind": "delivery_fee", "amount": "100000", "currency_code": "IRR"},
    )
    assert line.status_code == 201

    submitted = await client.post(
        f"/api/v1/settlements/{iid}/submit",
        headers=tenant_headers(TENANT_A),
        json={"version": version},
    )
    assert submitted.status_code == 200
    assert submitted.json()["status"] == "submitted"
    version = submitted.json()["version"]

    settled = await client.post(
        f"/api/v1/settlements/{iid}/settle",
        headers=tenant_headers(TENANT_A),
        json={"version": version},
    )
    assert settled.status_code == 200
    assert settled.json()["status"] == "settled"
    assert settled.json()["external_settlement_ref"] is not None
    assert settled.json()["external_settlement_ref"].startswith("acct://")

    events = {e.event_type for e in get_event_publisher().published}
    assert "delivery.settlement_intent.created" in events
    assert "delivery.settlement_intent.submitted" in events
    assert "delivery.settlement_intent.settled" in events
    assert "delivery.settlement_line.added" in events
