import { getTemplate } from './templates.js';

// ── Template Renderer ────────────────────────────────────────
// Simple {{variable}} interpolation. No external deps (Handlebars-like).

/**
 * Render a template by ID with the given variables.
 * Returns subject, bodyHtml, and bodyText with variables interpolated.
 * Throws if template not found.
 */
export function renderTemplate(
  templateId: string,
  variables: Record<string, string>
): { subject: string; bodyHtml: string; bodyText: string } {
  const template = getTemplate(templateId);
  if (!template) {
    throw new Error(`Email template '${templateId}' not found`);
  }

  return {
    subject: interpolate(template.subject, variables),
    bodyHtml: interpolate(template.bodyHtml, variables),
    bodyText: interpolate(template.bodyText, variables),
  };
}

/**
 * Replace all {{variableName}} occurrences with values from the map.
 * Unresolved variables are left as-is (no crash on missing).
 */
export function interpolate(text: string, variables: Record<string, string>): string {
  return text.replace(/\{\{(\w+)\}\}/g, (match, key: string) => {
    return key in variables ? variables[key] : match;
  });
}
