import { createHmac } from 'node:crypto';

// Pure token builder for the box terminal connection, extracted so it can be
// unit-tested without pulling in `server-only`/Convex. Mirrors the worker's
// `verifyBoxTerminalToken` format so the worker accepts the minted token:
//   `${expiresAtMs}.box.${username}.${hmacSha256Hex}`
// Returns null when the terminal feature is not configured (secret/WS base).
export const buildBoxToken = (
  username: string,
  secret: string | undefined,
  wsBase: string | undefined,
  now: number,
): { url: string; expiresAt: number } | null => {
  if (!secret || !wsBase) return null;
  const expiresAt = now + 2 * 60 * 1000;
  const payload = `${expiresAt}.box.${username}`;
  const signature = createHmac('sha256', secret).update(payload).digest('hex');
  const token = `${payload}.${signature}`;
  const url = `${wsBase.replace(/\/$/, '')}/box/terminal?token=${encodeURIComponent(token)}`;
  return { url, expiresAt };
};
