/**
 * Simple template engine for email templates
 *
 * Provides functions for rendering templates with context variables
 */

import fs from 'fs';
import path from 'path';

/**
 * Template engine class for rendering email templates
 */
export class TemplateEngine {
  private templatesDir: string;

  /**
   * Create a template engine instance
   *
   * @param templatesDir - Directory containing template files
   */
  constructor(templatesDir: string) {
    this.templatesDir = templatesDir;
  }

  /**
   * Render a template with context variables
   *
   * @param templateName - Name of the template (without extension)
   * @param context - Variables to inject into the template
   * @returns string - Rendered template
   */
  render(templateName: string, context: Record<string, any> = {}): string {
    const templatePath = path.join(this.templatesDir, `${templateName}.html`);

    try {
      let template = fs.readFileSync(templatePath, 'utf8');
      return this.renderTemplate(template, context);
    } catch (error) {
      console.error(`Failed to render template ${templateName}:`, error);
      throw new Error(
        `Template rendering failed: ${error instanceof Error ? error.message : String(error)}`
      );
    }
  }

  /**
   * Check if a template exists
   *
   * @param templateName - Name of the template (without extension)
   * @returns boolean - True if template exists
   */
  templateExists(templateName: string): boolean {
    const templatePath = path.join(this.templatesDir, `${templateName}.html`);
    return fs.existsSync(templatePath);
  }

  /**
   * Render template content with context variables
   * @private
   */
  private renderTemplate(template: string, context: Record<string, any>): string {
    let result = template;

    // Replace variables in the template
    Object.keys(context).forEach(key => {
      const value = context[key];
      const regex = new RegExp(`{{\\s*${key}\\s*}}`, 'g');
      result = result.replace(regex, String(value));
    });

    return result;
  }
}

/**
 * Render a template string with context variables
 *
 * @param template - Template string with {{variable}} placeholders
 * @param context - Variables to inject into the template
 * @returns string - Rendered template
 */
export function renderString(template: string, context: Record<string, any> = {}): string {
  const engine = new TemplateEngine('');
  return (engine as any).renderTemplate(template, context);
}
