import uuid

from app.db.redis import get_redis
from app.main import app
from app.models.delivery import DeliveryAssignment
from app.services import dispatch as dispatch_service

from .test_delivery import (  # noqa: F401 (fixture imports, used by name via injection)
    _checkout_delivery,
    _make_courier_available,
    admin_token,
    branch_and_item,
    courier,
    courier_token,
    customer_token,
    supplier_token,
)


def _fake_redis():
    return app.dependency_overrides[get_redis]()


def test_dispatch_lock_blocks_a_concurrent_dispatch_call(
    client,
    db_session,
    monkeypatch,
    customer_token,  # noqa: F811
    courier,  # noqa: F811
    courier_token,  # noqa: F811
    branch_and_item,  # noqa: F811
):
    """Simulates another in-flight dispatch call already holding the
    lock — proves a second call backs off instead of racing ahead and
    double-assigning a courier. Retry knobs turned down so this stays
    fast rather than actually waiting out the real 2-second window."""
    monkeypatch.setattr(dispatch_service, "_LOCK_MAX_WAIT_SECONDS", 0.2)
    monkeypatch.setattr(dispatch_service, "_LOCK_RETRY_INTERVAL_SECONDS", 0.02)

    branch, item = branch_and_item
    _make_courier_available(client, db_session, courier_token)

    redis = _fake_redis()
    assert dispatch_service._acquire_dispatch_lock(redis)  # held by "someone else"

    resp = _checkout_delivery(client, customer_token, item)
    assert resp.status_code == 200, resp.text

    # Couldn't get the lock in time -> no assignment was created at all.
    order_id = uuid.UUID(resp.json()["id"])
    assignments = (
        db_session.query(DeliveryAssignment)
        .filter(DeliveryAssignment.order_id == order_id)
        .all()
    )
    assert assignments == []


def test_dispatch_lock_is_released_after_a_successful_dispatch(
    client,
    db_session,
    customer_token,  # noqa: F811
    courier,  # noqa: F811
    courier_token,  # noqa: F811
    branch_and_item,  # noqa: F811
):
    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
    order_id = uuid.UUID(resp.json()["id"])
    assignments = (
        db_session.query(DeliveryAssignment)
        .filter(DeliveryAssignment.order_id == order_id)
        .all()
    )
    assert len(assignments) == 1  # dispatch actually ran, not blocked

    redis = _fake_redis()
    assert dispatch_service._acquire_dispatch_lock(redis)  # not left held


def test_dispatch_lock_is_released_even_when_no_courier_is_available(
    client,
    db_session,
    customer_token,  # noqa: F811
    branch_and_item,  # noqa: F811
):
    """No courier online at all — dispatch returns early (via the
    branch-None-check's sibling path, no candidates) — the lock must
    still be released via the `finally`, not leaked."""
    _branch, item = branch_and_item

    resp = _checkout_delivery(client, customer_token, item)
    assert resp.status_code == 200, resp.text

    redis = _fake_redis()
    assert dispatch_service._acquire_dispatch_lock(redis)
