# retoor <retoor@molodetz.nl>

from datetime import datetime, timedelta, timezone

from devplacepy.database import get_table
from devplacepy.utils import generate_uid
from devplacepy.services.messaging.tickets import issue_ticket, redeem_ticket


def _user_uid():
    uid = generate_uid()
    get_table("users").insert(
        {
            "uid": uid,
            "username": f"tkt_{uid[:8]}",
            "terms_version": "1",
            "email": f"{uid[:8]}@tkt.dev",
            "password_hash": "x",
            "role": "Member",
            "is_active": True,
            "created_at": datetime.now(timezone.utc).isoformat(),
        }
    )
    return uid


def test_ticket_redeems_once(local_db):
    user_uid = _user_uid()
    token = issue_ticket(user_uid)

    assert redeem_ticket(token) == user_uid
    assert redeem_ticket(token) is None


def test_expired_ticket_never_used_still_rejected(local_db):
    user_uid = _user_uid()
    token = issue_ticket(user_uid)

    expired_at = (datetime.now(timezone.utc) - timedelta(seconds=5)).isoformat()
    tickets = get_table("ws_tickets")
    row = tickets.find_one(token=token)
    tickets.update({"uid": row["uid"], "expires_at": expired_at}, ["uid"])

    assert redeem_ticket(token) is None


def test_redeem_unknown_token_returns_none(local_db):
    assert redeem_ticket("not-a-real-token") is None
