/**
 * 500-error alert email. Plain table of the request context plus the
 * stack — no branding, no CTA. It's read by developers, not customers.
 *
 * Only server-controlled values are interpolated. Request bodies,
 * headers and cookies are deliberately NOT included: they carry
 * passwords, tokens and PII (security.md — logging).
 */

export interface ErrorAlertTemplateInput {
  env: string;
  occurredAt: string;
  method: string;
  url: string;
  statusCode: number;
  message: string;
  /** Null when the thrown value carried no stack. */
  stack: string | null;
  tenantId: string | null;
  userId: string | null;
  requestId: string | null;
  /** How many times this same error fired during the mute window. */
  repeatCount: number;
}

export function errorAlertTemplate(input: ErrorAlertTemplateInput): {
  subject: string;
  html: string;
  text: string;
} {
  const rows: Array<[string, string]> = [
    ['When', input.occurredAt],
    ['Environment', input.env],
    ['Request', `${input.method} ${input.url}`],
    ['Status', String(input.statusCode)],
    ['Message', input.message],
    ['Tenant', input.tenantId || '—'],
    ['User', input.userId || '—'],
    ['Request id', input.requestId || '—'],
  ];
  if (input.repeatCount > 1) {
    rows.push(['Repeats', `${input.repeatCount} occurrences since the last alert`]);
  }

  const subject = `[${input.env}] 500 on ${input.method} ${input.url}`;

  const html = `
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>${escapeHtml(subject)}</title></head>
<body style="margin:0;padding:24px;background:#f6f6f6;font-family:Arial,sans-serif;color:#222;">
  <table role="presentation" cellspacing="0" cellpadding="0" border="0" width="640" style="background:#fff;border-radius:8px;border:1px solid #eee;">
    <tr><td style="padding:20px 24px;border-bottom:1px solid #eee;">
      <h1 style="margin:0;font-size:16px;color:#b91c1c;">Server error (500)</h1>
    </td></tr>
    <tr><td style="padding:20px 24px;">
      <table role="presentation" cellspacing="0" cellpadding="0" border="0" width="100%" style="font-size:13px;">
        ${rows
          .map(
            ([label, value]) => `<tr>
          <td style="padding:4px 12px 4px 0;color:#666;white-space:nowrap;vertical-align:top;">${escapeHtml(label)}</td>
          <td style="padding:4px 0;color:#222;word-break:break-word;">${escapeHtml(value)}</td>
        </tr>`,
          )
          .join('\n        ')}
      </table>
      ${
        input.stack
          ? `<pre style="margin:20px 0 0;padding:12px;background:#fafafa;border:1px solid #eee;border-radius:6px;font-size:12px;line-height:1.5;white-space:pre-wrap;word-break:break-word;color:#444;">${escapeHtml(input.stack)}</pre>`
          : ''
      }
    </td></tr>
  </table>
</body>
</html>
  `.trim();

  const text = [
    'Server error (500)',
    '',
    ...rows.map(([label, value]) => `${label}: ${value}`),
    '',
    input.stack || '(no stack trace)',
  ].join('\n');

  return { subject, html, text };
}

/** Same minimal escape as the password-reset template. */
function escapeHtml(s: string): string {
  return String(s)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}
