import { randomBytes } from 'node:crypto';

interface TokenEntry { userId: string; spaceId: string; expiresAt: number; }
const store = new Map<string, TokenEntry>();
const DEFAULT_TTL_MS = 120_000; // 1 test = 1 token, generous

export function mintAppHarnessToken(
  scope: { userId: string; spaceId: string },
  ttlMs: number = DEFAULT_TTL_MS,
): string {
  const token = randomBytes(24).toString('hex');
  store.set(token, { ...scope, expiresAt: Date.now() + ttlMs });
  return token;
}

export function verifyAppHarnessToken(token: string): { userId: string; spaceId: string } | null {
  const e = store.get(token);
  if (!e) return null;
  if (Date.now() > e.expiresAt) { store.delete(token); return null; }
  return { userId: e.userId, spaceId: e.spaceId };
}

export function revokeAppHarnessToken(token: string): void {
  store.delete(token);
}
