/**
 * Unsubscribe Token Utilities
 *
 * HMAC-based token generation and verification for one-click unsubscribe
 * compliance with RFC 8058 (Gmail/Yahoo/Microsoft requirements).
 *
 * @example
 * ```typescript
 * import { generateUnsubscribeToken, verifyUnsubscribeToken } from '@repo/core/server'
 *
 * // Generate token for email link
 * const token = generateUnsubscribeToken('john@example.com', process.env.UNSUBSCRIBE_SECRET!)
 * const url = `https://api.elevasis.io/api/unsubscribe?email=john@example.com&token=${token}`
 *
 * // Verify token on POST request
 * const isValid = verifyUnsubscribeToken('john@example.com', token, process.env.UNSUBSCRIBE_SECRET!)
 * ```
 */

import crypto from 'crypto'

/**
 * Generate HMAC-SHA256 token for unsubscribe verification
 *
 * Uses first 16 characters of the hash for URL-friendly tokens.
 *
 * @param email - Email address to generate token for
 * @param secret - HMAC secret key (HMAC_SECRET)
 * @returns 16-character hex token
 */
export function generateUnsubscribeToken(email: string, secret: string): string {
  return crypto.createHmac('sha256', secret).update(email.toLowerCase().trim()).digest('hex').slice(0, 16)
}

/**
 * Verify unsubscribe token using timing-safe comparison
 *
 * Prevents timing attacks by using constant-time comparison.
 *
 * @param email - Email address to verify
 * @param token - Token from request
 * @param secret - HMAC secret key (HMAC_SECRET)
 * @returns true if token is valid
 */
export function verifyUnsubscribeToken(email: string, token: string, secret: string): boolean {
  const expected = generateUnsubscribeToken(email, secret)

  // Ensure both are same length before comparison
  if (token.length !== expected.length) {
    return false
  }

  const tokenBuf = Buffer.from(token)
  const expectedBuf = Buffer.from(expected)

  return crypto.timingSafeEqual(tokenBuf, expectedBuf)
}

/**
 * Generate unsubscribe URL with token
 *
 * @param email - Email address
 * @param secret - HMAC secret key
 * @param baseUrl - Base URL for unsubscribe endpoint (default: production URL)
 * @returns Full unsubscribe URL with email and token query params
 */
export function generateUnsubscribeUrl(
  email: string,
  secret: string,
  baseUrl = 'https://api.elevasis.io/api/unsubscribe'
): string {
  const token = generateUnsubscribeToken(email, secret)
  const encodedEmail = encodeURIComponent(email.toLowerCase().trim())
  return `${baseUrl}?email=${encodedEmail}&token=${token}`
}

/**
 * Generate List-Unsubscribe headers for RFC 8058 compliance
 *
 * Returns headers object to include in Resend email headers parameter.
 *
 * @param email - Recipient email address
 * @param secret - HMAC secret key
 * @param baseUrl - Base URL for unsubscribe endpoint
 * @returns Headers object with List-Unsubscribe and List-Unsubscribe-Post
 *
 * @example
 * ```typescript
 * const headers = generateUnsubscribeHeaders('john@example.com', secret)
 * // Use in Resend:
 * await resend.emails.send({
 *   from: 'sender@domain.com',
 *   to: 'john@example.com',
 *   subject: 'Subject',
 *   html: '<p>Content</p>',
 *   headers
 * })
 * ```
 */
export function generateUnsubscribeHeaders(
  email: string,
  secret: string,
  baseUrl = 'https://api.elevasis.io/api/unsubscribe'
): Record<string, string> {
  const url = generateUnsubscribeUrl(email, secret, baseUrl)

  return {
    'List-Unsubscribe': `<${url}>`,
    'List-Unsubscribe-Post': 'List-Unsubscribe=One-Click'
  }
}
