"""Tests for in-memory is_duplicate_message fallback (no Redis required)."""

from unittest.mock import MagicMock

import pytest

from whatsapp.middleware.storage import InMemoryStore


def _make_client(store=None):
    """Build a minimal AzureBindingClient-like object backed by InMemoryStore."""
    from whatsapp.bindings.azure import AzureBindingClient

    bot = MagicMock()
    bot.inactivity_manager = MagicMock()
    bot.inactivity_manager.set_adapter = MagicMock()
    bot.session_store = store or InMemoryStore()
    bot.dialog_registry = {}
    bot.port = 8000

    azure_client = MagicMock()
    client = AzureBindingClient.__new__(AzureBindingClient)
    client.ctx = bot
    client.client = azure_client
    client.route = "/api/events"
    client.on_error = None
    client.channel_id = None
    client.on_message = None
    client._processed_messages = {}
    client.inactivity_manager = bot.inactivity_manager
    client.session_store = bot.session_store
    client.message = MagicMock()
    return client


@pytest.mark.asyncio
async def test_first_message_not_duplicate():
    client = _make_client()
    assert await client.is_duplicate_message("msg-001") is False


@pytest.mark.asyncio
async def test_second_message_is_duplicate():
    client = _make_client()
    await client.is_duplicate_message("msg-002")
    assert await client.is_duplicate_message("msg-002") is True


@pytest.mark.asyncio
async def test_different_ids_not_duplicate():
    client = _make_client()
    await client.is_duplicate_message("msg-003")
    assert await client.is_duplicate_message("msg-004") is False


@pytest.mark.asyncio
async def test_in_memory_keeps_last_10():
    """In-memory fallback should evict old entries after 10 messages."""
    client = _make_client()
    ids = [f"msg-{i}" for i in range(12)]
    for mid in ids:
        await client.is_duplicate_message(mid)

    # The first two should have been evicted
    assert await client.is_duplicate_message(ids[0]) is False
    assert await client.is_duplicate_message(ids[1]) is False
    # Recent ones should still be detected as duplicates
    assert await client.is_duplicate_message(ids[11]) is True
