/**
 * HMAC Token Utilities
 *
 * Generic HMAC-based token generation and verification.
 * Used for unsubscribe links, brochure personalization, and other marketing URLs.
 */

import crypto from 'crypto'

/**
 * Generate HMAC-SHA256 token for any data
 *
 * @param data - Data to sign (email, contactId, etc.)
 * @param secret - HMAC secret key (HMAC_SECRET)
 * @returns 16-character hex token
 */
export function generateHmacToken(data: string, secret: string): string {
  return crypto
    .createHmac('sha256', secret)
    .update(data.toLowerCase().trim())
    .digest('hex')
    .slice(0, 16)
}

/**
 * Verify HMAC token using timing-safe comparison
 */
export function verifyHmacToken(data: string, token: string, secret: string): boolean {
  const expected = generateHmacToken(data, secret)
  if (token.length !== expected.length) return false
  return crypto.timingSafeEqual(Buffer.from(token), Buffer.from(expected))
}

/**
 * Generate brochure URL with token
 */
export function generateBrochureUrl(
  contactId: string,
  secret: string,
  baseUrl = 'https://brochure.elevasis.io'
): string {
  const token = generateHmacToken(contactId, secret)
  return `${baseUrl}/${contactId}?t=${token}`
}
