/**
 * HTML escaping and URL validation for email template interpolation.
 * Default-safe: text vars are entity-escaped; href vars are https-validated + attr-escaped.
 */

/** Vars pre-built as trusted HTML fragments (e.g. adapter-rendered action buttons). */
export const TRUSTED_HTML_KEYS = new Set(['actionButtons'])

/** Vars interpolated into href attributes — https-only + attribute escaping. */
export const URL_ATTR_KEYS = new Set([
  'verificationUrl',
  'inviteUrl',
  'resetUrl',
  'link',
  'payment_link',
])

export function escapeHtmlText(value: string): string {
  return value
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;')
}

export function escapeHtmlAttr(value: string): string {
  return escapeHtmlText(value)
}

export function isAllowedHttpsUrl(url: string): boolean {
  try {
    return new URL(url).protocol === 'https:'
  } catch {
    return false
  }
}

export function prepareInterpolationValue(key: string, value: string): string {
  if (TRUSTED_HTML_KEYS.has(key)) {
    return value
  }
  if (URL_ATTR_KEYS.has(key)) {
    if (!isAllowedHttpsUrl(value)) {
      return ''
    }
    return escapeHtmlAttr(value)
  }
  return escapeHtmlText(value)
}

export function buildActionButtonsHtml(
  buttons: ReadonlyArray<{ label: string; url?: string }> | undefined,
): string {
  if (!buttons?.length) return ''

  return buttons
    .filter((b) => b.url && isAllowedHttpsUrl(b.url))
    .map(
      (b) =>
        `<a href="${escapeHtmlAttr(b.url!)}" style="display:inline-block;padding:10px 20px;background:#6b21a8;color:#fff;text-decoration:none;border-radius:var(--radius,4px);margin:4px;">${escapeHtmlText(b.label)}</a>`,
    )
    .join('\n')
}
