# retoor <retoor@molodetz.nl>

from datetime import datetime, timedelta, timezone

from devplacepy.database import get_table
from devplacepy.services.telegram import store


def _seed_user(uid: str) -> None:
    users = get_table("users")
    if not users.find_one(uid=uid):
        users.insert({"uid": uid, "username": uid, "api_key": f"key-{uid}"})


def test_issue_code_is_four_digits(local_db):
    _seed_user("tg-user-1")
    issued = store.issue_code("tg-user-1")
    assert issued["code"].isdigit() and len(issued["code"]) == 4
    assert issued["ttl_minutes"] >= 1


def test_verify_binds_and_is_single_use(local_db):
    _seed_user("tg-user-2")
    code = store.issue_code("tg-user-2")["code"]
    user = store.verify_code(code, chat_id=555, from_id=777)
    assert user is not None and user["uid"] == "tg-user-2"
    assert store.is_paired("tg-user-2")
    assert store.user_for_chat(555)["user_uid"] == "tg-user-2"
    assert store.verify_code(code, chat_id=555, from_id=777) is None


def test_reissue_invalidates_previous_code(local_db):
    _seed_user("tg-user-3")
    first = store.issue_code("tg-user-3")["code"]
    store.issue_code("tg-user-3")
    assert store.verify_code(first, chat_id=10, from_id=11) is None


def test_expired_code_rejected(local_db):
    _seed_user("tg-user-4")
    code = store.issue_code("tg-user-4")["code"]
    pairings = get_table("telegram_pairings")
    row = pairings.find_one(user_uid="tg-user-4", used=0)
    past = (datetime.now(timezone.utc) - timedelta(minutes=5)).isoformat()
    pairings.update({"id": row["id"], "expires_at": past}, ["id"])
    assert store.verify_code(code, chat_id=1, from_id=2) is None


def test_unpair_removes_link(local_db):
    _seed_user("tg-user-5")
    code = store.issue_code("tg-user-5")["code"]
    store.verify_code(code, chat_id=88, from_id=99)
    assert store.unpair("tg-user-5") == 1
    assert not store.is_paired("tg-user-5")


def test_verify_rejects_non_four_digit_code(local_db):
    assert store.verify_code("abcd", chat_id=1, from_id=2) is None
    assert store.verify_code("12345", chat_id=1, from_id=2) is None
    assert store.verify_code("12", chat_id=1, from_id=2) is None


def test_user_for_chat_unknown_is_none(local_db):
    assert store.user_for_chat(999_999) is None
    assert store.link_for_user("tg-no-such-user") is None


def test_unpair_unknown_user_removes_nothing(local_db):
    assert store.unpair("tg-never-paired") == 0


def test_rebind_moves_chat_to_latest_user(local_db):
    _seed_user("tg-user-6")
    _seed_user("tg-user-7")
    store.bind("tg-user-6", chat_id=4242, from_id=1)
    store.bind("tg-user-7", chat_id=4242, from_id=1)
    assert store.user_for_chat(4242)["user_uid"] == "tg-user-7"
    assert not store.is_paired("tg-user-6")
