/**
 * @ai-summary Simple template variable substitution service
 * @ai-context Replaces {{variableName}} with values
 */

import { renderEmailLayout } from './email-layout/base-layout';
import { EMAIL_STYLES } from './email-layout/email-styles';

export class TemplateService {
  /**
   * Render a template string by replacing {{variableName}} with values
   * @param template Template string with {{variable}} placeholders
   * @param variables Object mapping variable names to values
   * @returns Rendered string with variables replaced
   */
  render(template: string, variables: Record<string, string | number | boolean | null | undefined>): string {
    let result = template;

    for (const [key, value] of Object.entries(variables)) {
      const placeholder = `{{${key}}}`;
      const replacement = value !== null && value !== undefined ? String(value) : '';
      result = result.split(placeholder).join(replacement);
    }

    return result;
  }

  /**
   * Render a template as HTML email with branded layout
   * @param template Template string with {{variable}} placeholders
   * @param variables Object mapping variable names to values
   * @returns Complete HTML email string with layout wrapper
   */
  renderEmailHtml(template: string, variables: Record<string, string | number | boolean | null | undefined>): string {
    // 1. Replace variables in template body
    const renderedContent = this.render(template, variables);

    // 2. Escape HTML special characters to prevent XSS
    const escapeHtml = (text: string): string => {
      return text
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
    };

    // 3. Convert plain text line breaks to HTML paragraphs
    const htmlContent = renderedContent
      .split('\n')
      .map(line => line.trim())
      .filter(line => line.length > 0)
      .map(line => `<p style="${EMAIL_STYLES.paragraph}">${escapeHtml(line)}</p>`)
      .join('\n');

    // 4. Wrap in branded email layout
    return renderEmailLayout(htmlContent);
  }

  /**
   * Extract variable names from a template string
   * @param template Template string with {{variable}} placeholders
   * @returns Array of variable names found in template
   */
  extractVariables(template: string): string[] {
    const regex = /\{\{(\w+)\}\}/g;
    const variables: string[] = [];
    let match;

    while ((match = regex.exec(template)) !== null) {
      if (!variables.includes(match[1])) {
        variables.push(match[1]);
      }
    }

    return variables;
  }
}
