"""Phase 10.6 — Routing & Optimization tests."""
from __future__ import annotations

import pytest

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


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

    route = await client.post(
        "/api/v1/routes",
        headers=tenant_headers(TENANT_A),
        json={"organization_id": org_id, "code": "RT1"},
    )
    assert route.status_code == 201, route.text
    pid = route.json()["id"]

    stop = await client.post(
        f"/api/v1/routes/{pid}/stops",
        headers=tenant_headers(TENANT_A),
        json={"sequence": 0, "address_ref": "addr://1"},
    )
    assert stop.status_code == 201

    run = await client.post(
        "/api/v1/optimization/runs",
        headers=tenant_headers(TENANT_A),
        json={"route_plan_id": pid, "routing_engine_ref": "engine://default"},
    )
    assert run.status_code == 201, run.text
    assert run.json()["status"] == "completed"

    events = {e.event_type for e in get_event_publisher().published}
    assert "delivery.route_plan.created" in events
    assert "delivery.route_stop.added" in events
    assert "delivery.optimization_run.completed" in events
