"""A confirmed leave is submitted at most once (negative run, 28 Oct 2026, #37).

Two "yes" replies to the same card sent at once - a double tap, two tabs -
each loaded the draft at the start of their turn and each called
erp_client.apply_leave: two identical requests reached the approver. The chat
in-flight lock that would serialise them ships off, so the submit claims the
draft itself (services/leave_submit_claim.py).
"""
import asyncio
from contextlib import contextmanager
from datetime import date
from unittest.mock import AsyncMock, patch

import pytest

import services.leave_action_service as las
from services import leave_submit_claim

pytestmark = pytest.mark.asyncio

CARD = {
    "step": "awaiting_confirmation", "leave_type": "casual_leave",
    "from_date": "2026-11-05", "to_date": "2026-11-05",
    "session_type_slug": "full_day", "reason": "Personal work", "reason_confirmed": True,
}
_CONTEXT = {"http_status": 200, "body": {"success": True, "data": {
    "name": "T", "is_manager": False,
    "leave_quota": {"casual_leave": {"total": 12, "remaining": 8}},
    "leave_settings": {"leave_type": [{"slug": "casual_leave", "name": "Casual Leave",
                                       "session_type_required": False}]},
    "leaves": []}}}
_OK = {"http_status": 200, "body": {"success": True, "message": "Leave applied successfully.",
                                    "data": [{"id": 77, "from_date": "2026-11-05"}]}}
_REFUSED = {"http_status": 400, "body": {"success": False,
                                         "message": "Attendance is locked for date 2026-11-05"}}


@contextmanager
def _erp(apply_leave, slots=CARD):
    """Entered ONCE around every turn of a test. Not per turn: two patch
    blocks unwound out of order under asyncio.gather restore each other's
    patches, and the fake draft then leaks into every later test."""
    ok = AsyncMock(return_value=_CONTEXT)
    with patch.object(las.erp_client, "get_leave_context", ok), \
            patch.object(las.erp_client, "get_leave_balance", ok), \
            patch.object(las.erp_client, "get_applied_leaves", ok), \
            patch.object(las.erp_client, "apply_leave", apply_leave), \
            patch.object(las, "_today", lambda: date(2026, 10, 28)), \
            patch.object(las, "_call_llm", AsyncMock(side_effect=RuntimeError("no LLM"))), \
            patch.object(las.leave_slot_service, "get_slots", lambda *a, **k: dict(slots)), \
            patch.object(las.leave_slot_service, "set_slots", lambda *a, **k: True), \
            patch.object(las.leave_slot_service, "clear_slots", lambda *a, **k: True):
        yield


async def _yes(conv="once"):
    """One bare "yes" at the card. Each call loads its own copy of the draft,
    as two concurrent turns do."""
    out = await las.leave_action_node(
        {"query": "yes", "intent": "apply_leave", "bearer_token": "t", "company_id": 1,
         "conversation_id": conv, "usage_events": [], "is_manager": False},
        lambda ev: None)
    return out["response_text"]


def _slow_apply(calls, answer=_OK):
    async def _apply(*a, **k):
        calls.append(a[2])
        await asyncio.sleep(0.05)   # the erp round trip the second "yes" overlaps
        return answer
    return _apply


async def test_two_yeses_at_once_submit_one_leave():
    calls = []
    with _erp(_slow_apply(calls)):
        replies = await asyncio.gather(_yes(), _yes())
    assert calls == ["2026-11-05"], f"apply_leave called {len(calls)} times"
    assert sum("already being submitted" in r for r in replies) == 1, replies


async def test_a_yes_after_the_submit_finished_is_not_sent_again():
    """The slower duplicate can arrive after the first has completed - it
    still holds its copy of the draft, so the claim must outlive success."""
    calls = []
    with _erp(_slow_apply(calls)):
        await _yes()
        text = await _yes()
    assert calls == ["2026-11-05"]
    assert "already being submitted" in text


async def test_a_refused_submit_releases_the_claim_so_a_retry_can_send():
    calls = []
    with _erp(_slow_apply(calls, _REFUSED)):
        await _yes()
    with _erp(_slow_apply(calls)):
        await _yes()
    assert calls == ["2026-11-05", "2026-11-05"]


async def test_an_unreachable_erp_releases_the_claim():
    async def _down(*a, **k):
        raise las.erp_client.ErpApiUnavailable("down")
    with _erp(_down):
        await _yes()
    calls = []
    with _erp(_slow_apply(calls)):
        await _yes()
    assert calls == ["2026-11-05"]


async def test_a_different_request_in_the_same_chat_is_not_blocked():
    calls = []
    with _erp(_slow_apply(calls)):
        await _yes()
    with _erp(_slow_apply(calls), slots={**CARD, "from_date": "2026-11-06", "to_date": "2026-11-06"}):
        await _yes()
    assert calls == ["2026-11-05", "2026-11-06"]


def test_a_claim_held_by_another_worker_is_respected(fake_redis):
    """Redis is what makes the claim hold across workers: this process has
    no record of it, the shared store does."""
    fp = ("casual_leave", "2026-11-05", "2026-11-05", "full_day")
    assert leave_submit_claim.claim(1, "w", fp) is True
    leave_submit_claim._claims.clear()          # another worker: nothing in-process
    assert leave_submit_claim.claim(1, "w", fp) is False
    leave_submit_claim.release(1, "w", fp)
    assert leave_submit_claim.claim(1, "w", fp) is True
