/**
 * Password-reset email template.
 *
 * Inline HTML — kept here as a small render function rather than a
 * full templating engine to keep the dep tree clean. If/when we add
 * more email templates, swap to handlebars + a `templates/*.hbs`
 * folder; until then a typed render function is enough.
 *
 * Plain-text fallback returned alongside HTML for clients that
 * disable images / strip CSS — ensures the link is always visible.
 */

export interface PasswordResetTemplateInput {
  recipientName: string;
  /** Fully-formed reset URL including the tenant subdomain so the
   *  user lands on the right tenant's login after redemption. */
  resetUrl: string;
  /** Display string for the expiry, e.g. "30 minutes". */
  expiresIn: string;
  /** Tenant name for letterhead / "from <Tenant>" wording. */
  companyName: string;
}

export function passwordResetTemplate(input: PasswordResetTemplateInput): {
  html: string;
  text: string;
} {
  const { recipientName, resetUrl, expiresIn, companyName } = input;
  const safeName = recipientName ? escapeHtml(recipientName) : 'there';
  const safeCompany = escapeHtml(companyName);

  const html = `
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Reset your password</title>
</head>
<body style="margin:0;padding:0;background:#f6f6f6;font-family:Arial,sans-serif;color:#222;">
  <table role="presentation" cellspacing="0" cellpadding="0" border="0" width="100%" style="padding:32px 0;">
    <tr><td align="center">
      <table role="presentation" cellspacing="0" cellpadding="0" border="0" width="560" style="background:#ffffff;border-radius:8px;overflow:hidden;box-shadow:0 1px 4px rgba(0,0,0,.06);">
        <tr><td style="padding:24px 32px;border-bottom:1px solid #eee;">
          <h1 style="margin:0;font-size:18px;color:#1d4ed8;">${safeCompany}</h1>
        </td></tr>
        <tr><td style="padding:32px;">
          <p style="margin:0 0 16px;font-size:16px;">Hi ${safeName},</p>
          <p style="margin:0 0 16px;font-size:14px;line-height:1.55;">We received a request to reset the password for your ${safeCompany} account. Click the button below to choose a new password.</p>
          <p style="margin:24px 0;text-align:center;">
            <a href="${resetUrl}" style="display:inline-block;padding:12px 24px;background:#1d4ed8;color:#fff;text-decoration:none;border-radius:6px;font-weight:600;font-size:14px;">Reset password</a>
          </p>
          <p style="margin:0 0 8px;font-size:12px;color:#666;">If the button doesn't work, copy and paste this link into your browser:</p>
          <p style="margin:0 0 24px;font-size:12px;color:#666;word-break:break-all;"><a href="${resetUrl}" style="color:#1d4ed8;">${escapeHtml(resetUrl)}</a></p>
          <p style="margin:0 0 8px;font-size:13px;color:#444;">This link expires in <strong>${escapeHtml(expiresIn)}</strong> and can only be used once.</p>
          <p style="margin:0;font-size:13px;color:#444;">If you didn't request this, you can safely ignore this email — your password won't change.</p>
        </td></tr>
        <tr><td style="padding:16px 32px;background:#fafafa;border-top:1px solid #eee;text-align:center;">
          <p style="margin:0;font-size:11px;color:#999;">${safeCompany} · This is an automated email; please don't reply.</p>
        </td></tr>
      </table>
    </td></tr>
  </table>
</body>
</html>
  `.trim();

  const text = [
    `Hi ${recipientName || 'there'},`,
    '',
    `We received a request to reset the password for your ${companyName} account.`,
    '',
    `Reset link (expires in ${expiresIn}, single-use):`,
    resetUrl,
    '',
    `If you didn't request this, you can safely ignore this email — your password won't change.`,
    '',
    `— ${companyName}`,
  ].join('\n');

  return { html, text };
}

/**
 * Minimal HTML-entity escape for the small set of fields we
 * interpolate. Not a full sanitizer — we only ever interpolate
 * server-controlled / user-display strings, never raw user-typed
 * HTML. Per security.md A03 (XSS).
 */
function escapeHtml(s: string): string {
  return String(s)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}
