# retoor <retoor@molodetz.nl>

import secrets
from datetime import datetime, timedelta, timezone
from typing import Optional

from devplacepy.database import db, get_table
from devplacepy.utils import generate_uid

TICKET_KEY_BYTES = 24
TICKET_TTL_SECONDS = 30


def issue_ticket(user_uid: str) -> str:
    tickets = get_table("ws_tickets")
    token = secrets.token_hex(TICKET_KEY_BYTES)
    now = datetime.now(timezone.utc)
    expires_at = (now + timedelta(seconds=TICKET_TTL_SECONDS)).isoformat()
    tickets.insert(
        {
            "uid": generate_uid(),
            "token": token,
            "user_uid": user_uid,
            "created_at": now.isoformat(),
            "expires_at": expires_at,
            "used_at": None,
        }
    )
    return token


def redeem_ticket(token: str) -> Optional[str]:
    if not token:
        return None
    from sqlalchemy import text

    now = datetime.now(timezone.utc).isoformat()
    with db:
        result = db.executable.execute(
            text(
                "UPDATE ws_tickets SET used_at = :now"
                " WHERE token = :token AND used_at IS NULL AND expires_at >= :now"
            ),
            {"now": now, "token": token},
        )
        if result.rowcount != 1:
            return None
    tickets = get_table("ws_tickets")
    row = tickets.find_one(token=token)
    return row.get("user_uid") if row else None
