"""Tests for InactivityManager._send_presence_prompt and _auto_close with from_id (no Redis)."""

from unittest.mock import AsyncMock, MagicMock

import pytest

from whatsapp.middleware.inactivity import InactivityManager
from whatsapp.middleware.storage import InMemoryStore


def _make_manager():
    """Build an InactivityManager with a mock adapter (no Redis)."""
    manager = InactivityManager(
        prompt_message="Still there?",
        close_message="Closing.",
        inactivity_minutes=1,
        confirmation_minutes=1,
    )

    store = InMemoryStore()
    mock_client = MagicMock()
    mock_client.send = AsyncMock()

    adapter = MagicMock()
    adapter.session_store = store
    adapter.client = mock_client
    adapter.channel_id = "channel-abc"

    manager.set_adapter(adapter)
    return manager, adapter, mock_client


@pytest.mark.asyncio
async def test_send_presence_prompt_no_redis_sends_message():
    manager, adapter, mock_client = _make_manager()
    await manager._send_presence_prompt("user-1")
    mock_client.send.assert_called_once()


@pytest.mark.asyncio
async def test_send_presence_prompt_skips_when_awaiting():
    manager, adapter, mock_client = _make_manager()
    await adapter.session_store.set_awaiting_flag("user-2", True)
    await manager._send_presence_prompt("user-2")
    mock_client.send.assert_not_called()


@pytest.mark.asyncio
async def test_auto_close_no_redis_deletes_session():
    manager, adapter, mock_client = _make_manager()
    adapter.session_store.delete = AsyncMock()
    await manager._auto_close("user-3")
    adapter.session_store.delete.assert_called_once_with("user-3")


@pytest.mark.asyncio
async def test_auto_close_skips_when_awaiting():
    manager, adapter, mock_client = _make_manager()
    await adapter.session_store.set_awaiting_flag("user-4", True)
    adapter.session_store.delete = AsyncMock()
    await manager._auto_close("user-4")
    adapter.session_store.delete.assert_not_called()
    mock_client.send.assert_not_called()


@pytest.mark.asyncio
async def test_auto_close_removes_timer():
    manager, adapter, mock_client = _make_manager()
    # Put a fake timer entry in
    from whatsapp.middleware.inactivity import _UserTimers

    manager._timers["user-5"] = _UserTimers()
    adapter.session_store.delete = AsyncMock()
    await manager._auto_close("user-5")
    assert "user-5" not in manager._timers


@pytest.mark.asyncio
async def test_reset_starts_inactivity_task():
    manager, adapter, mock_client = _make_manager()
    await manager.reset("user-6")
    assert "user-6" in manager._timers
    assert manager._timers["user-6"].inactivity_task is not None
    # cleanup
    await manager.cancel("user-6")
