"""Unit tests for trusted_groups repository functions."""

import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from duty_teller.db.models import Base
from duty_teller.db.repository import (
    is_trusted_group,
    add_trusted_group,
    remove_trusted_group,
    get_all_trusted_group_ids,
)


@pytest.fixture
def session():
    """In-memory SQLite session with all tables (including trusted_groups)."""
    engine = create_engine(
        "sqlite:///:memory:", connect_args={"check_same_thread": False}
    )
    Base.metadata.create_all(engine)
    Session = sessionmaker(bind=engine, autocommit=False, autoflush=False)
    s = Session()
    try:
        yield s
    finally:
        s.close()
        engine.dispose()


def test_is_trusted_group_empty_returns_false(session):
    """is_trusted_group returns False when no record exists."""
    assert is_trusted_group(session, 100) is False
    assert is_trusted_group(session, 200) is False


def test_add_trusted_group_creates_record(session):
    """add_trusted_group creates a record and returns TrustedGroup."""
    record = add_trusted_group(session, 100, added_by_user_id=12345)
    assert record.chat_id == 100
    assert record.added_by_user_id == 12345
    assert record.added_at is not None


def test_is_trusted_group_after_add_returns_true(session):
    """is_trusted_group returns True after add_trusted_group."""
    add_trusted_group(session, 100)
    assert is_trusted_group(session, 100) is True
    assert is_trusted_group(session, 101) is False


def test_add_trusted_group_without_added_by_user_id(session):
    """add_trusted_group accepts added_by_user_id None."""
    record = add_trusted_group(session, 200, added_by_user_id=None)
    assert record.chat_id == 200
    assert record.added_by_user_id is None


def test_remove_trusted_group_removes_record(session):
    """remove_trusted_group removes the record."""
    add_trusted_group(session, 100)
    assert is_trusted_group(session, 100) is True
    remove_trusted_group(session, 100)
    assert is_trusted_group(session, 100) is False


def test_remove_trusted_group_idempotent(session):
    """remove_trusted_group on non-existent chat_id does not raise."""
    remove_trusted_group(session, 999)


def test_get_all_trusted_group_ids_empty(session):
    """get_all_trusted_group_ids returns empty list when no trusted groups."""
    assert get_all_trusted_group_ids(session) == []


def test_get_all_trusted_group_ids_returns_added_chats(session):
    """get_all_trusted_group_ids returns all trusted chat_ids."""
    add_trusted_group(session, 10)
    add_trusted_group(session, 20)
    add_trusted_group(session, 30)
    ids = get_all_trusted_group_ids(session)
    assert set(ids) == {10, 20, 30}
