# retoor <retoor@molodetz.nl>

from devplacepy.cli._shared import _audit_cli


def cmd_messaging_prune_tickets(args):
    from datetime import datetime, timezone
    from devplacepy.database import get_table

    now = datetime.now(timezone.utc).isoformat()
    tickets = get_table("ws_tickets")
    expired = list(tickets.find(expires_at={"<": now}))
    for ticket in expired:
        tickets.delete(uid=ticket["uid"])
    _audit_cli(
        "cli.messaging.prune_tickets",
        f"CLI pruned {len(expired)} expired WS tickets",
        metadata={"count": len(expired)},
    )
    print(f"Pruned {len(expired)} expired WS ticket(s)")


def register_messaging(subparsers):
    messaging = subparsers.add_parser("messaging", help="Messaging WS ticket management")
    messaging_sub = messaging.add_subparsers(title="action", dest="action")
    messaging_prune_tickets = messaging_sub.add_parser(
        "prune-tickets", help="Delete expired WebSocket auth tickets"
    )
    messaging_prune_tickets.set_defaults(func=cmd_messaging_prune_tickets)
