"""Phase 10.7 — Tracking & Proof of Delivery tests."""
from __future__ import annotations

from datetime import datetime, timezone

import pytest

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


async def _dispatch_job(client):
    org = await client.post(
        "/api/v1/organizations",
        headers=tenant_headers(TENANT_A),
        json={"code": "ORG_T107", "name": "Track Org", "status": "active"},
    )
    assert org.status_code == 201
    job = await client.post(
        "/api/v1/dispatch/jobs",
        headers=tenant_headers(TENANT_A),
        json={"organization_id": org.json()["id"], "code": "TJ1"},
    )
    assert job.status_code == 201
    return job.json()["id"]


@pytest.mark.asyncio
async def test_tracking_pod_and_customer_token(client):
    jid = await _dispatch_job(client)

    session = await client.post(
        "/api/v1/tracking/sessions",
        headers=tenant_headers(TENANT_A),
        json={"dispatch_job_id": jid},
    )
    assert session.status_code == 201, session.text
    sid = session.json()["id"]

    point = await client.post(
        f"/api/v1/tracking/sessions/{sid}/points",
        headers=tenant_headers(TENANT_A),
        json={
            "latitude": 35.6892,
            "longitude": 51.389,
            "recorded_at": datetime.now(timezone.utc).isoformat(),
        },
    )
    assert point.status_code == 201

    pod = await client.post(
        "/api/v1/proof-of-delivery",
        headers=tenant_headers(TENANT_A),
        json={
            "dispatch_job_id": jid,
            "signature_file_ref": "storage://pod/sig-1",
        },
    )
    assert pod.status_code == 201, pod.text

    token = await client.post(
        "/api/v1/customer-tracking/tokens",
        headers=tenant_headers(TENANT_A),
        json={"dispatch_job_id": jid},
    )
    assert token.status_code == 201, token.text
    assert token.json()["token"]

    events = {e.event_type for e in get_event_publisher().published}
    assert "delivery.tracking_session.started" in events
    assert "delivery.tracking_point.recorded" in events
    assert "delivery.proof_of_delivery.captured" in events
    assert "delivery.customer_tracking_token.created" in events
