"""Phase 10.3 — Availability, Shifts & Working Zones tests."""
from __future__ import annotations

from datetime import datetime, timedelta, timezone

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


@pytest.mark.asyncio
async def test_availability_shift_zone_flow(client):
    org = await _org(client)
    driver = await client.post(
        "/api/v1/drivers",
        headers=tenant_headers(TENANT_A),
        json={
            "organization_id": org["id"],
            "code": "DRV_A103",
            "display_name": "Shift Driver",
            "status": "active",
        },
    )
    assert driver.status_code == 201
    did = driver.json()["id"]

    avail = await client.put(
        f"/api/v1/drivers/{did}/availability",
        headers=tenant_headers(TENANT_A),
        json={"status": "online"},
    )
    assert avail.status_code == 200, avail.text
    assert avail.json()["status"] == "online"

    start = datetime.now(timezone.utc)
    end = start + timedelta(hours=8)
    shift = await client.post(
        "/api/v1/shifts",
        headers=tenant_headers(TENANT_A),
        json={
            "organization_id": org["id"],
            "code": "SH1",
            "name": "Morning",
            "starts_at": start.isoformat(),
            "ends_at": end.isoformat(),
        },
    )
    assert shift.status_code == 201, shift.text
    sid = shift.json()["id"]

    assign = await client.post(
        f"/api/v1/shifts/{sid}/assignments",
        headers=tenant_headers(TENANT_A),
        json={"driver_id": did},
    )
    assert assign.status_code == 201

    zone = await client.post(
        "/api/v1/working-zones",
        headers=tenant_headers(TENANT_A),
        json={
            "organization_id": org["id"],
            "code": "ZN1",
            "name": "North Zone",
        },
    )
    assert zone.status_code == 201, zone.text

    events = {e.event_type for e in get_event_publisher().published}
    assert "delivery.driver_availability.updated" in events
    assert "delivery.shift.created" in events
    assert "delivery.working_zone.created" in events
