from __future__ import annotations

from beaver.interfaces.channels.connections import (
    ChannelConnectionStore,
    CredentialStore,
    PairingTokenStore,
)


def test_channel_connection_store_creates_updates_lists_and_revokes(tmp_path) -> None:
    store = ChannelConnectionStore(tmp_path / "connections.json")

    created = store.create(
        kind="telegram",
        mode="polling",
        display_name="Telegram Main",
        account_id="telegram:bot-main",
        owner_user_id="user-1",
        auth_type="token",
        runtime_config={"max_message_chars": 4096},
        capabilities=["receive_text", "send_text"],
    )
    updated = store.update_status(created.connection_id, status="connected", last_error=None)
    revoked = store.revoke(created.connection_id)

    assert created.connection_id
    assert created.channel_id.startswith("telegram-")
    assert created.status == "draft"
    assert updated.status == "connected"
    assert revoked.status == "revoked"
    assert store.get(created.connection_id).status == "revoked"
    assert [item.connection_id for item in store.list()] == [created.connection_id]


def test_credential_store_saves_values_by_reference_and_redacts_views(tmp_path) -> None:
    store = CredentialStore(tmp_path / "credentials.json")

    ref = store.put(kind="telegram", values={"botToken": "secret-token", "empty": ""})

    assert ref.startswith("cred_")
    assert store.get(ref) == {"botToken": "secret-token"}
    assert store.redacted(ref) == {"botToken": "***"}


def test_pairing_token_store_uses_one_time_expiring_tokens(tmp_path) -> None:
    store = PairingTokenStore(tmp_path / "pairing.json")

    session = store.create(kind="terminal", ttl_seconds=60, scope="channel:pair")
    consumed = store.consume(session.token, expected_kind="terminal")
    reused = store.consume(session.token, expected_kind="terminal")

    assert session.status == "pending"
    assert consumed is not None
    assert consumed.status == "consumed"
    assert reused is None


def test_pairing_token_store_rejects_expired_tokens(tmp_path) -> None:
    store = PairingTokenStore(tmp_path / "pairing.json")

    session = store.create(kind="weixin", ttl_seconds=-1, scope="channel:pair")

    assert store.consume(session.token, expected_kind="weixin") is None
