from __future__ import annotations

import importlib
import pytest


@pytest.fixture(autouse=True)
def fresh_db(tmp_path, monkeypatch):
    monkeypatch.setenv("DB_PATH", str(tmp_path / "test.db"))
    import adapter.telegram.db as db_mod
    importlib.reload(db_mod)
    db_mod.init_db()
    return db_mod


def test_create_and_get_chat(fresh_db):
    db = fresh_db
    db.create_chat(user_id=1, thread_id=100, chat_name="Чат #1")
    chat = db.get_chat(user_id=1, thread_id=100)
    assert chat is not None
    assert chat["chat_name"] == "Чат #1"
    assert chat["archived_at"] is None


def test_get_chat_missing(fresh_db):
    assert fresh_db.get_chat(user_id=1, thread_id=999) is None


def test_archive_chat(fresh_db):
    db = fresh_db
    db.create_chat(1, 100, "Чат #1")
    db.archive_chat(1, 100)
    chat = db.get_chat(1, 100)
    assert chat["archived_at"] is not None


def test_rename_chat(fresh_db):
    db = fresh_db
    db.create_chat(1, 100, "Чат #1")
    db.rename_chat(1, 100, "Новое имя")
    assert db.get_chat(1, 100)["chat_name"] == "Новое имя"


def test_get_active_chats(fresh_db):
    db = fresh_db
    db.create_chat(1, 100, "Чат #1")
    db.create_chat(1, 200, "Чат #2")
    db.archive_chat(1, 100)
    chats = db.get_active_chats(1)
    assert len(chats) == 1
    assert chats[0]["thread_id"] == 200


def test_display_number(fresh_db):
    db = fresh_db
    db.create_chat(1, 100, "Чат #1")
    db.create_chat(1, 200, "Чат #2")
    db.create_chat(1, 300, "Чат #3")
    assert db.get_display_number(1, 100) == 1
    assert db.get_display_number(1, 200) == 2
    assert db.get_display_number(1, 300) == 3


def test_count_active_chats(fresh_db):
    db = fresh_db
    db.create_chat(1, 100, "Чат #1")
    db.create_chat(1, 200, "Чат #2")
    db.archive_chat(1, 100)
    assert db.count_active_chats(1) == 1


def test_different_users_isolated(fresh_db):
    db = fresh_db
    db.create_chat(1, 100, "Чат #1")
    db.create_chat(2, 100, "Чат #1")  # same thread_id, different user
    assert db.get_chat(1, 100)["chat_name"] == "Чат #1"
    assert db.get_chat(2, 100)["chat_name"] == "Чат #1"
    db.archive_chat(1, 100)
    assert db.get_chat(1, 100)["archived_at"] is not None
    assert db.get_chat(2, 100)["archived_at"] is None
