"""Phase 10.2 — Fleet & Vehicle 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, code="ORG_F102"):
    resp = await client.post(
        "/api/v1/organizations",
        headers=tenant_headers(TENANT_A),
        json={"code": code, "name": code, "status": "active"},
    )
    assert resp.status_code == 201, resp.text
    return resp.json()


async def _vehicle_type(client, code="VT1"):
    resp = await client.post(
        "/api/v1/vehicle-types",
        headers=tenant_headers(TENANT_A),
        json={"code": code, "name": f"Type {code}"},
    )
    assert resp.status_code == 201, resp.text
    return resp.json()


@pytest.mark.asyncio
async def test_fleet_vehicle_crud_and_assignment(client):
    org = await _org(client)
    vt = await _vehicle_type(client, "VAN")

    fleet = await client.post(
        "/api/v1/fleets",
        headers=tenant_headers(TENANT_A),
        json={
            "organization_id": org["id"],
            "code": "FL1",
            "name": "Main Fleet",
            "status": "active",
        },
    )
    assert fleet.status_code == 201, fleet.text
    fleet_body = fleet.json()

    vehicle = await client.post(
        "/api/v1/vehicles",
        headers=tenant_headers(TENANT_A),
        json={
            "fleet_id": fleet_body["id"],
            "vehicle_type_id": vt["id"],
            "code": "VH1",
            "plate_number": "12A345-11",
        },
    )
    assert vehicle.status_code == 201, vehicle.text
    vid = vehicle.json()["id"]

    driver = await client.post(
        "/api/v1/drivers",
        headers=tenant_headers(TENANT_A),
        json={
            "organization_id": org["id"],
            "code": "DRV_F102",
            "display_name": "Fleet Driver",
            "status": "active",
        },
    )
    assert driver.status_code == 201
    did = driver.json()["id"]

    assign = await client.post(
        f"/api/v1/vehicles/{vid}/assignments",
        headers=tenant_headers(TENANT_A),
        json={"driver_id": did},
    )
    assert assign.status_code == 201, assign.text
    assert assign.json()["status"] == "active"

    listed = await client.get(
        "/api/v1/vehicles",
        headers=tenant_headers(TENANT_A),
        params={"fleet_id": fleet_body["id"]},
    )
    assert listed.status_code == 200
    assert listed.json()["total"] == 1

    events = {e.event_type for e in get_event_publisher().published}
    assert "delivery.fleet.created" in events
    assert "delivery.vehicle.created" in events
    assert "delivery.vehicle_assignment.created" in events
