import hashlib
import hmac
import json
import uuid
from datetime import datetime, time, timedelta, timezone

import pytest

from app.core import security
from app.models.delivery import CourierProfile
from app.models.order import Order, OrderStatus, PaymentStatus
from app.models.user import User, UserRole
from app.utils.phone import normalize_ethiopian_phone
from app.utils.time import utcnow

SUPPLIER_PHONE = "0961000001"
ADMIN_PHONE = "0961000002"
CUSTOMER_PHONE = "0961000003"
COURIER_PHONE = "0961000004"
COURIER2_PHONE = "0961000005"
SEED_PIN = "111111"

# Covers the whole day, regardless of when the test suite actually runs.
ALL_DAY_SHIFT = {"shift_start": "00:00:00", "shift_end": "23:59:59"}

# Near the branch used in `branch_and_item` below.
NEAR_BRANCH = {"latitude": 9.006, "longitude": 38.764}


def _addis_weekday_now() -> int:
    """Mirrors app.services.dispatch._addis_local_weekday so
    working_days tests are deterministic regardless of when the suite
    actually runs."""
    return (datetime.now(timezone.utc) + timedelta(hours=3)).weekday()


def _seed_user(db_session, phone, name, role, pin=SEED_PIN, email=None):
    normalized = normalize_ethiopian_phone(phone)
    user = User(
        phone=normalized,
        name=name,
        email=email or f"{normalized.lstrip('+')}@example.com",
        role=role.value,
        pin_hash=security.hash_pin(pin),
        is_phone_verified=True,
        is_email_verified=True,
    )
    db_session.add(user)
    db_session.commit()
    db_session.refresh(user)
    return user


def _login(client, phone, pin=SEED_PIN) -> str:
    resp = client.post("/api/v1/auth/login", json={"identifier": phone, "pin": pin})
    assert resp.status_code == 200, resp.text
    return resp.json()["access_token"]


def _auth_headers(token: str) -> dict:
    return {"Authorization": f"Bearer {token}"}


@pytest.fixture()
def supplier_token(client, db_session):
    _seed_user(db_session, SUPPLIER_PHONE, "A Supplier", UserRole.SUPPLIER)
    return _login(client, SUPPLIER_PHONE)


@pytest.fixture()
def admin_token(client, db_session):
    _seed_user(db_session, ADMIN_PHONE, "An Admin", UserRole.ADMIN)
    return _login(client, ADMIN_PHONE)


@pytest.fixture()
def customer_token(client, db_session):
    _seed_user(db_session, CUSTOMER_PHONE, "A Customer", UserRole.CUSTOMER)
    return _login(client, CUSTOMER_PHONE)


@pytest.fixture()
def courier(db_session):
    return _seed_user(db_session, COURIER_PHONE, "A Courier", UserRole.COURIER)


@pytest.fixture()
def courier_token(client, courier):
    return _login(client, COURIER_PHONE)


@pytest.fixture()
def courier2(db_session):
    return _seed_user(db_session, COURIER2_PHONE, "Another Courier", UserRole.COURIER)


@pytest.fixture()
def courier2_token(client, courier2):
    return _login(client, COURIER2_PHONE)


@pytest.fixture()
def branch_and_item(client, supplier_token, admin_token):
    merchant = client.post(
        "/api/v1/merchants",
        json={"name": "Wow Burger"},
        headers=_auth_headers(supplier_token),
    ).json()
    branch = client.post(
        f"/api/v1/merchants/{merchant['id']}/branches",
        json={
            "name": "Bole Branch",
            "address": "Bole, Addis Ababa",
            "latitude": 9.005,
            "longitude": 38.763,
            "phone": "0911223344",
        },
        headers=_auth_headers(supplier_token),
    ).json()
    client.patch(
        f"/api/v1/branches/{branch['id']}/approve",
        json={"approval_status": "approved"},
        headers=_auth_headers(admin_token),
    )
    category = client.post(
        f"/api/v1/branches/{branch['id']}/categories",
        json={"name": "Mains"},
        headers=_auth_headers(supplier_token),
    ).json()
    item = client.post(
        f"/api/v1/branches/{branch['id']}/categories/{category['id']}/items",
        json={"name": "Beef Burger", "price": "150.00"},
        headers=_auth_headers(supplier_token),
    ).json()
    return branch, item


def _set_profile(db_session, courier_token, **fields):
    """Sets CourierProfile fields directly via the DB — the admin
    endpoint that actually sets these in production
    (PATCH /admin/couriers/{id}) gets its own dedicated tests below;
    this is just fixture setup so the rest of the suite doesn't have
    to thread an admin login through every call site."""
    courier_id = uuid.UUID(security.decode_access_token(courier_token)["sub"])
    profile = (
        db_session.query(CourierProfile)
        .filter(CourierProfile.user_id == courier_id)
        .first()
    )
    for field, value in fields.items():
        setattr(profile, field, value)
    db_session.commit()


def _make_courier_available(client, db_session, courier_token, **location_overrides):
    location = {**NEAR_BRANCH, **location_overrides}
    resp = client.post(
        "/api/v1/courier/location", json=location, headers=_auth_headers(courier_token)
    )
    assert resp.status_code == 200, resp.text
    _set_profile(
        db_session,
        courier_token,
        is_online=True,
        shift_start=time.fromisoformat("00:00:00"),
        shift_end=time.fromisoformat("23:59:59"),
    )


def _checkout_delivery(
    client,
    customer_token,
    item,
    payment_method="cash",
    address="Kazanchis, Addis Ababa",
    latitude=9.010,
    longitude=38.768,
):
    client.post(
        "/api/v1/cart/items",
        json={"menu_item_id": item["id"], "quantity": 1},
        headers=_auth_headers(customer_token),
    )
    return client.post(
        "/api/v1/orders/checkout",
        json={
            "delivery_mode": "delivery",
            "delivery_address": address,
            "delivery_latitude": latitude,
            "delivery_longitude": longitude,
            "payment_method": payment_method,
        },
        headers=_auth_headers(customer_token),
    )


# --- Courier profile -------------------------------------------------------


def test_courier_profile_defaults_offline_with_no_shift(client, courier_token):
    resp = client.get("/api/v1/courier/profile", headers=_auth_headers(courier_token))
    assert resp.status_code == 200, resp.text
    body = resp.json()
    assert body["is_online"] is False
    assert body["shift_start"] is None
    assert body["shift_end"] is None


def test_post_location_requires_courier_role(client, customer_token):
    resp = client.post(
        "/api/v1/courier/location",
        json=NEAR_BRANCH,
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 403


# --- Admin sets shift + online/offline (couriers are full-time staff, not
# gig workers who set their own schedule) -----------------------------------


def test_admin_can_set_courier_shift_and_online(client, admin_token, courier):
    resp = client.patch(
        f"/api/v1/admin/couriers/{courier.id}",
        json={"is_online": True, **ALL_DAY_SHIFT},
        headers=_auth_headers(admin_token),
    )
    assert resp.status_code == 200, resp.text
    body = resp.json()
    assert body["is_online"] is True
    assert body["shift_start"] == "00:00:00"
    assert body["shift_end"] == "23:59:59"
    assert body["user_id"] == str(courier.id)
    assert body["working_days"] == [0, 1, 2, 3, 4, 5, 6]  # default: every day


def test_admin_can_set_working_days(client, admin_token, courier):
    resp = client.patch(
        f"/api/v1/admin/couriers/{courier.id}",
        json={"working_days": [0, 1, 2, 3, 4]},  # weekdays only
        headers=_auth_headers(admin_token),
    )
    assert resp.status_code == 200, resp.text
    assert resp.json()["working_days"] == [0, 1, 2, 3, 4]


def test_working_days_rejects_empty_list(client, admin_token, courier):
    resp = client.patch(
        f"/api/v1/admin/couriers/{courier.id}",
        json={"working_days": []},
        headers=_auth_headers(admin_token),
    )
    assert resp.status_code == 422


def test_working_days_rejects_out_of_range_day(client, admin_token, courier):
    resp = client.patch(
        f"/api/v1/admin/couriers/{courier.id}",
        json={"working_days": [0, 7]},
        headers=_auth_headers(admin_token),
    )
    assert resp.status_code == 422


def test_working_days_rejects_duplicate_day(client, admin_token, courier):
    resp = client.patch(
        f"/api/v1/admin/couriers/{courier.id}",
        json={"working_days": [0, 0, 1]},
        headers=_auth_headers(admin_token),
    )
    assert resp.status_code == 422


def test_admin_can_update_single_field_without_touching_others(
    client, admin_token, courier
):
    client.patch(
        f"/api/v1/admin/couriers/{courier.id}",
        json={"is_online": True, **ALL_DAY_SHIFT},
        headers=_auth_headers(admin_token),
    )
    resp = client.patch(
        f"/api/v1/admin/couriers/{courier.id}",
        json={"is_online": False},
        headers=_auth_headers(admin_token),
    )
    assert resp.status_code == 200, resp.text
    body = resp.json()
    assert body["is_online"] is False
    assert body["shift_start"] == "00:00:00"  # untouched by the is_online-only patch
    assert body["shift_end"] == "23:59:59"


def test_courier_can_read_back_admin_set_profile(
    client, admin_token, courier_token, courier
):
    client.patch(
        f"/api/v1/admin/couriers/{courier.id}",
        json={"is_online": True, **ALL_DAY_SHIFT},
        headers=_auth_headers(admin_token),
    )
    resp = client.get("/api/v1/courier/profile", headers=_auth_headers(courier_token))
    assert resp.status_code == 200, resp.text
    body = resp.json()
    assert body["is_online"] is True
    assert body["shift_start"] == "00:00:00"


def test_courier_profile_update_rejects_non_admin(client, supplier_token, courier):
    resp = client.patch(
        f"/api/v1/admin/couriers/{courier.id}",
        json={"is_online": True},
        headers=_auth_headers(supplier_token),
    )
    assert resp.status_code == 403


def test_courier_profile_update_404s_for_non_courier_user(
    client, admin_token, db_session
):
    non_courier = _seed_user(db_session, "0961000008", "A Customer", UserRole.CUSTOMER)
    resp = client.patch(
        f"/api/v1/admin/couriers/{non_courier.id}",
        json={"is_online": True},
        headers=_auth_headers(admin_token),
    )
    assert resp.status_code == 404


def test_offline_courier_not_dispatched(
    client, db_session, customer_token, courier_token, branch_and_item
):
    _branch, item = branch_and_item
    client.post(
        "/api/v1/courier/location",
        json=NEAR_BRANCH,
        headers=_auth_headers(courier_token),
    )
    _set_profile(
        db_session,
        courier_token,
        shift_start=time.fromisoformat("00:00:00"),
        shift_end=time.fromisoformat("23:59:59"),
    )
    # Deliberately never flip is_online — stays offline (the default).

    _checkout_delivery(client, customer_token, item)
    offer = client.get(
        "/api/v1/courier/offers/current", headers=_auth_headers(courier_token)
    )
    assert offer.status_code == 404


def test_courier_not_scheduled_today_not_dispatched(
    client, db_session, customer_token, courier_token, branch_and_item
):
    _branch, item = branch_and_item
    other_day = (_addis_weekday_now() + 1) % 7
    client.post(
        "/api/v1/courier/location",
        json=NEAR_BRANCH,
        headers=_auth_headers(courier_token),
    )
    _set_profile(
        db_session,
        courier_token,
        is_online=True,
        shift_start=time.fromisoformat("00:00:00"),
        shift_end=time.fromisoformat("23:59:59"),
        working_days=[other_day],  # every day except today
    )

    _checkout_delivery(client, customer_token, item)
    offer = client.get(
        "/api/v1/courier/offers/current", headers=_auth_headers(courier_token)
    )
    assert offer.status_code == 404


def test_courier_scheduled_today_is_dispatched(
    client, db_session, customer_token, courier_token, branch_and_item
):
    _branch, item = branch_and_item
    client.post(
        "/api/v1/courier/location",
        json=NEAR_BRANCH,
        headers=_auth_headers(courier_token),
    )
    _set_profile(
        db_session,
        courier_token,
        is_online=True,
        shift_start=time.fromisoformat("00:00:00"),
        shift_end=time.fromisoformat("23:59:59"),
        working_days=[_addis_weekday_now()],
    )

    _checkout_delivery(client, customer_token, item)
    offer = client.get(
        "/api/v1/courier/offers/current", headers=_auth_headers(courier_token)
    )
    assert offer.status_code == 200, offer.text


# --- Dispatch on checkout ----------------------------------------------


def test_cash_delivery_checkout_dispatches_to_available_courier(
    client, db_session, customer_token, courier_token, branch_and_item
):
    _branch, item = branch_and_item
    _make_courier_available(client, db_session, courier_token)

    resp = _checkout_delivery(client, customer_token, item)
    assert resp.status_code == 200, resp.text
    assert resp.json()["status"] == "confirmed"  # cash skips PENDING_PAYMENT

    offer = client.get(
        "/api/v1/courier/offers/current", headers=_auth_headers(courier_token)
    )
    assert offer.status_code == 200, offer.text
    assert offer.json()["order_id"] == resp.json()["id"]
    assert offer.json()["status"] == "offered"
    assert offer.json()["branch_name"] == "Bole Branch"


def test_cash_takeaway_checkout_does_not_dispatch(
    client, db_session, customer_token, courier_token, branch_and_item
):
    _branch, item = branch_and_item
    _make_courier_available(client, db_session, courier_token)

    client.post(
        "/api/v1/cart/items",
        json={"menu_item_id": item["id"], "quantity": 1},
        headers=_auth_headers(customer_token),
    )
    client.post(
        "/api/v1/orders/checkout",
        json={"delivery_mode": "takeaway", "payment_method": "cash"},
        headers=_auth_headers(customer_token),
    )

    offer = client.get(
        "/api/v1/courier/offers/current", headers=_auth_headers(courier_token)
    )
    assert offer.status_code == 404


def test_checkout_with_no_courier_available_leaves_order_unassigned(
    client, customer_token, branch_and_item
):
    _branch, item = branch_and_item
    resp = _checkout_delivery(client, customer_token, item)
    assert resp.status_code == 200, resp.text
    # No courier exists at all — order is simply unassigned, not an error.


def test_courier_off_shift_not_dispatched(
    client, db_session, customer_token, courier_token, branch_and_item
):
    _branch, item = branch_and_item
    client.post(
        "/api/v1/courier/location",
        json=NEAR_BRANCH,
        headers=_auth_headers(courier_token),
    )  # no shift set at all -> never on shift
    _set_profile(db_session, courier_token, is_online=True)

    _checkout_delivery(client, customer_token, item)
    offer = client.get(
        "/api/v1/courier/offers/current", headers=_auth_headers(courier_token)
    )
    assert offer.status_code == 404


def test_courier_stale_location_not_dispatched(
    client, db_session, customer_token, courier, courier_token, branch_and_item
):
    _branch, item = branch_and_item
    client.post(
        "/api/v1/courier/location",
        json=NEAR_BRANCH,
        headers=_auth_headers(courier_token),
    )
    _set_profile(
        db_session,
        courier_token,
        is_online=True,
        shift_start=time.fromisoformat("00:00:00"),
        shift_end=time.fromisoformat("23:59:59"),
    )
    profile = (
        db_session.query(CourierProfile)
        .filter(CourierProfile.user_id == courier.id)
        .first()
    )
    profile.last_location_at = utcnow() - timedelta(minutes=30)
    db_session.commit()

    _checkout_delivery(client, customer_token, item)
    offer = client.get(
        "/api/v1/courier/offers/current", headers=_auth_headers(courier_token)
    )
    assert offer.status_code == 404


# --- Offer accept/reject -------------------------------------------------


def test_courier_accept_offer(
    client, db_session, customer_token, courier_token, branch_and_item
):
    _branch, item = branch_and_item
    _make_courier_available(client, db_session, courier_token)
    _checkout_delivery(client, customer_token, item)

    offer = client.get(
        "/api/v1/courier/offers/current", headers=_auth_headers(courier_token)
    ).json()
    resp = client.post(
        f"/api/v1/courier/offers/{offer['id']}/accept",
        headers=_auth_headers(courier_token),
    )
    assert resp.status_code == 200, resp.text
    assert resp.json()["status"] == "accepted"


def test_courier_reject_offer_with_no_other_courier_available(
    client, db_session, customer_token, courier_token, branch_and_item
):
    _branch, item = branch_and_item
    _make_courier_available(client, db_session, courier_token)
    _checkout_delivery(client, customer_token, item)

    offer = client.get(
        "/api/v1/courier/offers/current", headers=_auth_headers(courier_token)
    ).json()
    resp = client.post(
        f"/api/v1/courier/offers/{offer['id']}/reject",
        headers=_auth_headers(courier_token),
    )
    assert resp.status_code == 200, resp.text
    assert resp.json()["status"] == "rejected"

    still_no_offer = client.get(
        "/api/v1/courier/offers/current", headers=_auth_headers(courier_token)
    )
    assert still_no_offer.status_code == 404


# Reassigning to the next-*nearest* courier when 2+ are eligible requires
# an actual PostGIS ST_Distance tie-break (see
# app.services.dispatch.dispatch_next_courier) — same as branch distance
# sorting in app.api.v1.endpoints.merchants, this only runs against
# real Postgres and is verified there, not in this SQLite-backed suite.
# The single-candidate reject path above (no reassignment possible) is
# what's covered here.


def test_courier_cannot_act_on_someone_elses_assignment(
    client, db_session, customer_token, courier_token, courier2_token, branch_and_item
):
    _branch, item = branch_and_item
    _make_courier_available(client, db_session, courier_token)
    _checkout_delivery(client, customer_token, item)

    offer = client.get(
        "/api/v1/courier/offers/current", headers=_auth_headers(courier_token)
    ).json()
    resp = client.post(
        f"/api/v1/courier/offers/{offer['id']}/accept",
        headers=_auth_headers(courier2_token),
    )
    assert resp.status_code == 404


# --- Pickup / delivery lifecycle -----------------------------------------


def _dispatch_and_accept(client, db_session, customer_token, courier_token, item):
    _make_courier_available(client, db_session, courier_token)
    order = _checkout_delivery(client, customer_token, item).json()
    offer = client.get(
        "/api/v1/courier/offers/current", headers=_auth_headers(courier_token)
    ).json()
    client.post(
        f"/api/v1/courier/offers/{offer['id']}/accept",
        headers=_auth_headers(courier_token),
    )
    return order, offer["id"]


def test_pickup_requires_accepted_first(
    client, db_session, customer_token, courier_token, branch_and_item
):
    _branch, item = branch_and_item
    _make_courier_available(client, db_session, courier_token)
    _checkout_delivery(client, customer_token, item)
    offer = client.get(
        "/api/v1/courier/offers/current", headers=_auth_headers(courier_token)
    ).json()

    resp = client.post(
        f"/api/v1/courier/deliveries/{offer['id']}/picked-up",
        headers=_auth_headers(courier_token),
    )
    assert resp.status_code == 409


def test_deliver_requires_picked_up_first(
    client, db_session, customer_token, courier_token, branch_and_item
):
    _branch, item = branch_and_item
    _order, assignment_id = _dispatch_and_accept(
        client, db_session, customer_token, courier_token, item
    )

    resp = client.post(
        f"/api/v1/courier/deliveries/{assignment_id}/delivered",
        headers=_auth_headers(courier_token),
    )
    assert resp.status_code == 409


def test_full_delivery_lifecycle_completes_cash_order_and_marks_paid(
    client, db_session, customer_token, courier_token, branch_and_item
):
    _branch, item = branch_and_item
    order, assignment_id = _dispatch_and_accept(
        client, db_session, customer_token, courier_token, item
    )

    pickup = client.post(
        f"/api/v1/courier/deliveries/{assignment_id}/picked-up",
        headers=_auth_headers(courier_token),
    )
    assert pickup.status_code == 200, pickup.text
    assert pickup.json()["status"] == "picked_up"

    delivered = client.post(
        f"/api/v1/courier/deliveries/{assignment_id}/delivered",
        headers=_auth_headers(courier_token),
    )
    assert delivered.status_code == 200, delivered.text
    assert delivered.json()["status"] == "delivered"

    db_order = (
        db_session.query(Order).filter(Order.id == uuid.UUID(order["id"])).first()
    )
    assert db_order.status == OrderStatus.COMPLETED.value
    assert db_order.payment_status == PaymentStatus.PAID.value


# --- Order status endpoint interaction ------------------------------------


def test_staff_cannot_complete_delivery_order_directly(
    client, db_session, supplier_token, customer_token, courier_token, branch_and_item
):
    _branch, item = branch_and_item
    order, _assignment_id = _dispatch_and_accept(
        client, db_session, customer_token, courier_token, item
    )
    db_order = (
        db_session.query(Order).filter(Order.id == uuid.UUID(order["id"])).first()
    )
    db_order.status = OrderStatus.READY.value
    db_session.commit()

    resp = client.patch(
        f"/api/v1/orders/{order['id']}/status",
        json={"status": "completed"},
        headers=_auth_headers(supplier_token),
    )
    assert resp.status_code == 409


def test_staff_can_progress_cash_delivery_order_without_payment(
    client, db_session, supplier_token, customer_token, courier_token, branch_and_item
):
    """Cash orders start CONFIRMED with payment_status still pending —
    branch staff must still be able to move them through preparing/ready
    without waiting for payment, unlike Chapa orders."""
    _branch, item = branch_and_item
    order, _assignment_id = _dispatch_and_accept(
        client, db_session, customer_token, courier_token, item
    )

    resp = client.patch(
        f"/api/v1/orders/{order['id']}/status",
        json={"status": "preparing"},
        headers=_auth_headers(supplier_token),
    )
    assert resp.status_code == 200, resp.text
    assert resp.json()["status"] == "preparing"


# --- Customer/staff tracking -----------------------------------------------


def test_tracking_snapshot_shows_assigned_courier(
    client, db_session, customer_token, courier, courier_token, branch_and_item
):
    _branch, item = branch_and_item
    order, assignment_id = _dispatch_and_accept(
        client, db_session, customer_token, courier_token, item
    )

    resp = client.get(
        f"/api/v1/orders/{order['id']}/tracking", headers=_auth_headers(customer_token)
    )
    assert resp.status_code == 200, resp.text
    body = resp.json()
    assert body["assignment_status"] == "accepted"
    assert body["courier_name"] == courier.name
    assert body["last_latitude"] == NEAR_BRANCH["latitude"]
    assert assignment_id  # sanity: fixture actually created one


def test_tracking_404s_for_unrelated_customer(
    client, db_session, customer_token, courier_token, branch_and_item
):
    _branch, item = branch_and_item
    order, _assignment_id = _dispatch_and_accept(
        client, db_session, customer_token, courier_token, item
    )
    _seed_user(db_session, "0961000009", "Someone Else", UserRole.CUSTOMER)
    other_token = _login(client, "0961000009")

    resp = client.get(
        f"/api/v1/orders/{order['id']}/tracking", headers=_auth_headers(other_token)
    )
    assert resp.status_code == 404


def test_tracking_visible_to_branch_staff(
    client, db_session, supplier_token, customer_token, courier_token, branch_and_item
):
    _branch, item = branch_and_item
    order, _assignment_id = _dispatch_and_accept(
        client, db_session, customer_token, courier_token, item
    )

    resp = client.get(
        f"/api/v1/orders/{order['id']}/tracking", headers=_auth_headers(supplier_token)
    )
    assert resp.status_code == 200, resp.text


# --- Chapa (non-cash) dispatch happens via webhook, not checkout -----------

WEBHOOK_SECRET = "test-webhook-secret"


def _sign(body: dict) -> tuple[bytes, str]:
    raw = json.dumps(body).encode()
    signature = hmac.new(WEBHOOK_SECRET.encode(), raw, hashlib.sha256).hexdigest()
    return raw, signature


def test_chapa_delivery_checkout_does_not_dispatch_before_payment(
    client, db_session, customer_token, courier_token, branch_and_item
):
    _branch, item = branch_and_item
    _make_courier_available(client, db_session, courier_token)

    resp = _checkout_delivery(client, customer_token, item, payment_method="chapa")
    assert resp.status_code == 200, resp.text
    assert resp.json()["status"] == "pending_payment"

    offer = client.get(
        "/api/v1/courier/offers/current", headers=_auth_headers(courier_token)
    )
    assert offer.status_code == 404


def test_chapa_webhook_success_dispatches_courier_for_delivery_order(
    client, db_session, monkeypatch, customer_token, courier_token, branch_and_item
):
    from app.core.config import settings
    from app.services.payments import chapa as chapa_service

    _branch, item = branch_and_item
    _make_courier_available(client, db_session, courier_token)

    order = _checkout_delivery(
        client, customer_token, item, payment_method="chapa"
    ).json()

    monkeypatch.setattr(settings, "chapa_webhook_secret", WEBHOOK_SECRET)
    monkeypatch.setattr(
        chapa_service, "verify_payment", lambda tx_ref: {"status": "success"}
    )
    raw, sig = _sign({"tx_ref": order["tx_ref"], "event": "charge.success"})
    headers = {"Content-Type": "application/json", "x-chapa-signature": sig}
    webhook_resp = client.post("/api/v1/webhooks/chapa", content=raw, headers=headers)
    assert webhook_resp.status_code == 200

    offer = client.get(
        "/api/v1/courier/offers/current", headers=_auth_headers(courier_token)
    )
    assert offer.status_code == 200, offer.text
    assert offer.json()["order_id"] == order["id"]


# --- Delivery history (distinct from earnings) ------------------------------


def test_list_deliveries_empty_for_new_courier(client, courier_token):
    resp = client.get(
        "/api/v1/courier/deliveries", headers=_auth_headers(courier_token)
    )
    assert resp.status_code == 200, resp.text
    assert resp.json() == []


def test_list_deliveries_shows_offered_assignment(
    client, db_session, customer_token, courier_token, branch_and_item
):
    _branch, item = branch_and_item
    _make_courier_available(client, db_session, courier_token)
    order = _checkout_delivery(client, customer_token, item).json()

    resp = client.get(
        "/api/v1/courier/deliveries", headers=_auth_headers(courier_token)
    )
    assert resp.status_code == 200, resp.text
    rows = resp.json()
    assert len(rows) == 1
    assert rows[0]["status"] == "offered"
    assert rows[0]["order_id"] == order["id"]
    assert rows[0]["branch_name"] == "Bole Branch"
    assert rows[0]["total"] == order["total"]


def test_list_deliveries_shows_rejected_assignment(
    client, db_session, customer_token, courier_token, branch_and_item
):
    _branch, item = branch_and_item
    _make_courier_available(client, db_session, courier_token)
    _checkout_delivery(client, customer_token, item)

    offer = client.get(
        "/api/v1/courier/offers/current", headers=_auth_headers(courier_token)
    ).json()
    client.post(
        f"/api/v1/courier/offers/{offer['id']}/reject",
        headers=_auth_headers(courier_token),
    )

    resp = client.get(
        "/api/v1/courier/deliveries", headers=_auth_headers(courier_token)
    )
    assert resp.status_code == 200, resp.text
    assert resp.json()[0]["status"] == "rejected"


def test_list_deliveries_shows_completed_delivery(
    client, db_session, customer_token, courier_token, branch_and_item
):
    _branch, item = branch_and_item
    order, assignment_id = _dispatch_and_accept(
        client, db_session, customer_token, courier_token, item
    )
    client.post(
        f"/api/v1/courier/deliveries/{assignment_id}/picked-up",
        headers=_auth_headers(courier_token),
    )
    client.post(
        f"/api/v1/courier/deliveries/{assignment_id}/delivered",
        headers=_auth_headers(courier_token),
    )

    resp = client.get(
        "/api/v1/courier/deliveries", headers=_auth_headers(courier_token)
    )
    assert resp.status_code == 200, resp.text
    row = resp.json()[0]
    assert row["status"] == "delivered"
    assert row["order_status"] == "completed"
    assert row["delivery_address"] == order["delivery_address"]


def test_list_deliveries_scoped_to_own_courier(
    client, db_session, customer_token, courier_token, courier2_token, branch_and_item
):
    _branch, item = branch_and_item
    _make_courier_available(client, db_session, courier_token)
    _checkout_delivery(client, customer_token, item)

    mine = client.get(
        "/api/v1/courier/deliveries", headers=_auth_headers(courier_token)
    ).json()
    other = client.get(
        "/api/v1/courier/deliveries", headers=_auth_headers(courier2_token)
    ).json()
    assert len(mine) == 1
    assert other == []


def test_list_deliveries_requires_courier_role(client, customer_token):
    resp = client.get(
        "/api/v1/courier/deliveries", headers=_auth_headers(customer_token)
    )
    assert resp.status_code == 403
