# tests/core/test_chat.py
import pytest
from core.chat import ChatManager
from core.store import InMemoryStore
from sdk.mock import MockPlatformClient


@pytest.fixture
def mgr():
    return ChatManager(MockPlatformClient(), InMemoryStore())


async def test_get_or_create_new_chat(mgr):
    ctx = await mgr.get_or_create("u1", "C1", "telegram", "topic-123")
    assert ctx.chat_id == "C1"
    assert ctx.platform == "telegram"
    assert ctx.is_archived is False


async def test_get_or_create_idempotent(mgr):
    c1 = await mgr.get_or_create("u1", "C1", "telegram", "t1")
    c2 = await mgr.get_or_create("u1", "C1", "telegram", "t1")
    assert c1.chat_id == c2.chat_id
    assert c1.display_name == c2.display_name


async def test_get_or_create_with_custom_name(mgr):
    ctx = await mgr.get_or_create("u1", "C1", "telegram", "t1", name="Анализ рынка")
    assert ctx.display_name == "Анализ рынка"


async def test_rename_chat(mgr):
    await mgr.get_or_create("u1", "C1", "telegram", "t1")
    ctx = await mgr.rename("C1", "Новое название")
    assert ctx.display_name == "Новое название"


async def test_archive_chat(mgr):
    await mgr.get_or_create("u1", "C1", "telegram", "t1")
    await mgr.archive("C1")
    ctx = await mgr.get("C1")
    assert ctx is not None
    assert ctx.is_archived is True


async def test_list_active_excludes_archived(mgr):
    await mgr.get_or_create("u1", "C1", "telegram", "t1")
    await mgr.get_or_create("u1", "C2", "telegram", "t2")
    await mgr.archive("C2")
    chats = await mgr.list_active("u1")
    ids = [c.chat_id for c in chats]
    assert "C1" in ids
    assert "C2" not in ids
