import { createHmac, timingSafeEqual } from 'node:crypto';

/**
 * VIP Ark Blueprint access links carry an HMAC of the result code. Only the server can mint one,
 * and it does so only after a payment provider confirms the purchase.
 */
const DEV_SECRET = 'dev-only-insecure-report-secret';

function reportSecret(): string {
  const secret = process.env.REPORT_TOKEN_SECRET;
  if (secret && secret.length >= 16) return secret;
  if (process.env.NODE_ENV === 'production') {
    throw new Error('REPORT_TOKEN_SECRET must be set (16+ characters) in production.');
  }
  return DEV_SECRET;
}

export function createReportToken(code: string, secret = reportSecret()): string {
  return createHmac('sha256', secret).update(`founder-report:v1:${code}`).digest('base64url').slice(0, 32);
}

export function verifyReportToken(code: string, token: string | null | undefined, secret = reportSecret()): boolean {
  if (!token) return false;
  const expected = Buffer.from(createReportToken(code, secret));
  const actual = Buffer.from(token);
  return expected.length === actual.length && timingSafeEqual(expected, actual);
}
