"use strict";
/**
 * Enhanced Email Generator
 * Generates comprehensive email infrastructure
 *
 * Features:
 * - Email service integration (SendGrid, Postmark, Resend, AWS SES)
 * - Email templates (welcome, password reset, verification, notifications)
 * - Template rendering (Handlebars/React Email)
 * - Email queue for async sending
 * - Email tracking (opens, clicks)
 * - Unsubscribe handling
 * - Email testing utilities
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.enhancedEmailGenerator = exports.EnhancedEmailGenerator = void 0;
const path = __importStar(require("path"));
class EnhancedEmailGenerator {
    id = 'enhanced-email';
    name = 'Enhanced Email Generator';
    description = 'Generates comprehensive email infrastructure with multi-provider support, templates, and tracking';
    generate(context) {
        const { workflow, outputDirectory } = context;
        const files = [];
        if (!workflow.email) {
            return { files };
        }
        const email = workflow.email;
        // Generate email configuration
        files.push(this.generateEmailConfig(email, outputDirectory));
        // Generate email service
        files.push(this.generateEmailService(email, outputDirectory));
        // Generate email provider integration
        files.push(this.generateEmailProvider(email, outputDirectory));
        // Generate email templates
        if (email.templates && email.templates.length > 0) {
            files.push(...this.generateEmailTemplates(email, outputDirectory));
        }
        // Generate template renderer
        if (email.rendering) {
            files.push(this.generateTemplateRenderer(email, outputDirectory));
        }
        // Generate email queue
        if (email.queue?.enabled) {
            files.push(this.generateEmailQueue(email, outputDirectory));
            files.push(this.generateEmailWorker(email, outputDirectory));
        }
        // Generate tracking utilities
        if (email.tracking) {
            files.push(this.generateEmailTracking(email, outputDirectory));
        }
        // Generate unsubscribe handler
        if (email.unsubscribe?.enabled) {
            files.push(this.generateUnsubscribeHandler(email, outputDirectory));
        }
        // Generate testing utilities
        if (email.testing) {
            files.push(this.generateEmailTesting(email, outputDirectory));
        }
        return { files };
    }
    generateEmailConfig(email, outputDirectory) {
        const content = `/**
 * Email Configuration
 * Generated by Bangstack
 */

export const emailConfig = {
  provider: '${email.provider}',
  config: {
    apiKey: process.env.EMAIL_API_KEY || '',
    fromEmail: process.env.EMAIL_FROM || '${email.config?.from_email || 'noreply@example.com'}',
    fromName: '${email.config?.from_name || 'App Name'}',
  },
  ${email.rendering ? `rendering: {
    engine: '${email.rendering.engine}',
    templatesPath: '${email.rendering.templates_path || './templates/email'}',
  },` : ''}
  ${email.queue?.enabled ? `queue: {
    enabled: true,
    redisUrl: process.env.REDIS_URL || '${email.queue.redis_url || 'redis://localhost:6379'}',
    concurrency: ${email.queue.concurrency || 5},
  },` : 'queue: { enabled: false },'}
  ${email.tracking ? `tracking: {
    opens: ${email.tracking.opens !== false},
    clicks: ${email.tracking.clicks !== false},
    provider: '${email.tracking.provider || 'internal'}',
  },` : ''}
  ${email.unsubscribe?.enabled ? `unsubscribe: {
    enabled: true,
    linkType: '${email.unsubscribe.link_type || 'one_click'}',
  },` : ''}
  ${email.testing ? `testing: {
    mode: process.env.EMAIL_TEST_MODE || '${email.testing.mode || 'real'}',
    catchAllEmail: process.env.EMAIL_CATCH_ALL || '${email.testing.catch_all_email || ''}',
  },` : ''}
};

export default emailConfig;
`;
        return {
            path: path.join(outputDirectory, 'api/src/config/email.ts'),
            content,
        };
    }
    generateEmailService(email, outputDirectory) {
        const content = `/**
 * Email Service
 * Generated by Bangstack
 */

import { emailConfig } from '../config/email';
import { emailProvider } from './email-provider';
${email.rendering ? "import { renderTemplate } from './email-renderer';" : ''}
${email.queue?.enabled ? "import { emailQueue } from './email-queue';" : ''}
${email.tracking ? "import { trackEmail } from './email-tracking';" : ''}

export interface EmailData {
  to: string | string[];
  subject: string;
  html?: string;
  text?: string;
  template?: string;
  variables?: Record<string, any>;
  attachments?: EmailAttachment[];
}

export interface EmailAttachment {
  filename: string;
  content: Buffer | string;
  contentType?: string;
}

export interface EmailResult {
  success: boolean;
  messageId?: string;
  error?: string;
}

export class EmailService {
  /**
   * Send an email
   */
  async send(data: EmailData): Promise<EmailResult> {
    try {
      // Apply test mode if enabled
      if (emailConfig.testing?.mode === 'mock') {
        console.log('Email mocked:', data);
        return { success: true, messageId: 'mock-id' };
      }

      if (emailConfig.testing?.mode === 'log') {
        console.log('Email logged:', data);
      }

      // Override recipient in test mode
      if (emailConfig.testing?.catchAllEmail) {
        data.to = emailConfig.testing.catchAllEmail;
      }

      // Render template if specified
      if (data.template) {
        ${email.rendering ? `
        const rendered = await renderTemplate(data.template, data.variables || {});
        data.html = rendered.html;
        data.text = rendered.text;
        data.subject = rendered.subject || data.subject;
        ` : `throw new Error('Template rendering not configured');`}
      }

      // Queue email if enabled
      ${email.queue?.enabled ? `
      if (emailConfig.queue.enabled) {
        await emailQueue.add('send-email', data);
        return { success: true, messageId: 'queued' };
      }
      ` : ''}

      // Send email directly
      const result = await emailProvider.send({
        from: {
          email: emailConfig.config.fromEmail,
          name: emailConfig.config.fromName,
        },
        to: Array.isArray(data.to) ? data.to : [data.to],
        subject: data.subject,
        html: data.html || '',
        text: data.text,
        attachments: data.attachments,
      });

      ${email.tracking ? `
      // Track email if enabled
      if (emailConfig.tracking && result.messageId) {
        await trackEmail({
          messageId: result.messageId,
          to: data.to,
          subject: data.subject,
          template: data.template,
        });
      }
      ` : ''}

      return result;
    } catch (error) {
      console.error('Email send error:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error',
      };
    }
  }

  /**
   * Send a transactional email using a template
   */
  async sendTransactional(
    to: string,
    template: string,
    variables: Record<string, any>
  ): Promise<EmailResult> {
    return this.send({
      to,
      subject: '', // Will be set by template
      template,
      variables,
    });
  }

  /**
   * Send bulk emails (batch)
   */
  async sendBulk(emails: EmailData[]): Promise<EmailResult[]> {
    return Promise.all(emails.map(email => this.send(email)));
  }
}

export const emailService = new EmailService();
`;
        return {
            path: path.join(outputDirectory, 'api/src/services/email-service.ts'),
            content,
        };
    }
    generateEmailProvider(email, outputDirectory) {
        const provider = email.provider;
        let content = '';
        if (provider === 'sendgrid') {
            content = `/**
 * SendGrid Email Provider
 * Generated by Bangstack
 */

import sgMail from '@sendgrid/mail';
import { emailConfig } from '../config/email';

sgMail.setApiKey(emailConfig.config.apiKey);

export interface SendEmailParams {
  from: { email: string; name: string };
  to: string[];
  subject: string;
  html: string;
  text?: string;
  attachments?: any[];
}

export const emailProvider = {
  async send(params: SendEmailParams): Promise<{ success: boolean; messageId?: string }> {
    try {
      const [response] = await sgMail.send({
        from: params.from,
        to: params.to,
        subject: params.subject,
        html: params.html,
        text: params.text,
        attachments: params.attachments,
      });

      return {
        success: true,
        messageId: response.headers['x-message-id'] as string,
      };
    } catch (error) {
      throw error;
    }
  },
};
`;
        }
        else if (provider === 'postmark') {
            content = `/**
 * Postmark Email Provider
 * Generated by Bangstack
 */

import * as postmark from 'postmark';
import { emailConfig } from '../config/email';

const client = new postmark.ServerClient(emailConfig.config.apiKey);

export interface SendEmailParams {
  from: { email: string; name: string };
  to: string[];
  subject: string;
  html: string;
  text?: string;
  attachments?: any[];
}

export const emailProvider = {
  async send(params: SendEmailParams): Promise<{ success: boolean; messageId?: string }> {
    try {
      const result = await client.sendEmail({
        From: \`\${params.from.name} <\${params.from.email}>\`,
        To: params.to.join(','),
        Subject: params.subject,
        HtmlBody: params.html,
        TextBody: params.text,
        Attachments: params.attachments,
      });

      return {
        success: true,
        messageId: result.MessageID,
      };
    } catch (error) {
      throw error;
    }
  },
};
`;
        }
        else if (provider === 'resend') {
            content = `/**
 * Resend Email Provider
 * Generated by Bangstack
 */

import { Resend } from 'resend';
import { emailConfig } from '../config/email';

const resend = new Resend(emailConfig.config.apiKey);

export interface SendEmailParams {
  from: { email: string; name: string };
  to: string[];
  subject: string;
  html: string;
  text?: string;
  attachments?: any[];
}

export const emailProvider = {
  async send(params: SendEmailParams): Promise<{ success: boolean; messageId?: string }> {
    try {
      const result = await resend.emails.send({
        from: \`\${params.from.name} <\${params.from.email}>\`,
        to: params.to,
        subject: params.subject,
        html: params.html,
        text: params.text,
        attachments: params.attachments,
      });

      return {
        success: true,
        messageId: result.id,
      };
    } catch (error) {
      throw error;
    }
  },
};
`;
        }
        else if (provider === 'ses') {
            content = `/**
 * AWS SES Email Provider
 * Generated by Bangstack
 */

import { SESClient, SendEmailCommand } from '@aws-sdk/client-ses';
import { emailConfig } from '../config/email';

const ses = new SESClient({
  region: process.env.AWS_REGION || 'us-east-1',
});

export interface SendEmailParams {
  from: { email: string; name: string };
  to: string[];
  subject: string;
  html: string;
  text?: string;
  attachments?: any[];
}

export const emailProvider = {
  async send(params: SendEmailParams): Promise<{ success: boolean; messageId?: string }> {
    try {
      const command = new SendEmailCommand({
        Source: \`\${params.from.name} <\${params.from.email}>\`,
        Destination: {
          ToAddresses: params.to,
        },
        Message: {
          Subject: {
            Data: params.subject,
          },
          Body: {
            Html: {
              Data: params.html,
            },
            ...(params.text ? { Text: { Data: params.text } } : {}),
          },
        },
      });

      const result = await ses.send(command);

      return {
        success: true,
        messageId: result.MessageId,
      };
    } catch (error) {
      throw error;
    }
  },
};
`;
        }
        return {
            path: path.join(outputDirectory, 'api/src/services/email-provider.ts'),
            content,
        };
    }
    generateEmailTemplates(email, outputDirectory) {
        const files = [];
        const templates = email.templates || [];
        templates.forEach(template => {
            const content = `<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>${template.subject}</title>
</head>
<body>
  <h1>${template.subject}</h1>
  <p>This is a template for ${template.name}</p>

  ${template.variables?.map(variable => `<p>{{${variable}}}</p>`).join('\n  ') || ''}
</body>
</html>
`;
            files.push({
                path: path.join(outputDirectory, `api/templates/email/${template.name}.html`),
                content,
            });
        });
        return files;
    }
    generateTemplateRenderer(email, outputDirectory) {
        const engine = email.rendering?.engine || 'handlebars';
        let content = '';
        if (engine === 'handlebars') {
            content = `/**
 * Handlebars Email Template Renderer
 * Generated by Bangstack
 */

import Handlebars from 'handlebars';
import * as fs from 'fs/promises';
import * as path from 'path';
import { emailConfig } from '../config/email';

export interface RenderedEmail {
  html: string;
  text?: string;
  subject?: string;
}

/**
 * Render email template
 */
export async function renderTemplate(
  templateName: string,
  variables: Record<string, any>
): Promise<RenderedEmail> {
  const templatePath = path.join(
    __dirname,
    '../../',
    emailConfig.rendering.templatesPath,
    \`\${templateName}.html\`
  );

  const templateSource = await fs.readFile(templatePath, 'utf-8');
  const template = Handlebars.compile(templateSource);
  const html = template(variables);

  return { html };
}
`;
        }
        else if (engine === 'react_email') {
            content = `/**
 * React Email Template Renderer
 * Generated by Bangstack
 */

import { render } from '@react-email/render';
import * as path from 'path';

export interface RenderedEmail {
  html: string;
  text?: string;
  subject?: string;
}

/**
 * Render email template
 */
export async function renderTemplate(
  templateName: string,
  variables: Record<string, any>
): Promise<RenderedEmail> {
  // Import template component dynamically
  const templatePath = path.join(__dirname, '../../templates/email', templateName);
  const TemplateComponent = (await import(templatePath)).default;

  const html = render(<TemplateComponent {...variables} />);

  return { html };
}
`;
        }
        return {
            path: path.join(outputDirectory, 'api/src/services/email-renderer.ts'),
            content,
        };
    }
    generateEmailQueue(email, outputDirectory) {
        const content = `/**
 * Email Queue
 * Generated by Bangstack
 */

import { Queue } from 'bullmq';
import { emailConfig } from '../config/email';

export const emailQueue = new Queue('email', {
  connection: {
    url: emailConfig.queue.redisUrl,
  },
  defaultJobOptions: {
    attempts: 3,
    backoff: {
      type: 'exponential',
      delay: 1000,
    },
    removeOnComplete: 100,
    removeOnFail: 1000,
  },
});

/**
 * Close queue connection
 */
export async function closeEmailQueue(): Promise<void> {
  await emailQueue.close();
}
`;
        return {
            path: path.join(outputDirectory, 'api/src/queues/email-queue.ts'),
            content,
        };
    }
    generateEmailWorker(email, outputDirectory) {
        const content = `/**
 * Email Worker
 * Processes email queue jobs
 * Generated by Bangstack
 */

import { Worker } from 'bullmq';
import { emailConfig } from '../config/email';
import { emailProvider } from '../services/email-provider';

export const emailWorker = new Worker(
  'email',
  async (job) => {
    const { to, subject, html, text, attachments } = job.data;

    await emailProvider.send({
      from: {
        email: emailConfig.config.fromEmail,
        name: emailConfig.config.fromName,
      },
      to: Array.isArray(to) ? to : [to],
      subject,
      html,
      text,
      attachments,
    });
  },
  {
    connection: {
      url: emailConfig.queue.redisUrl,
    },
    concurrency: emailConfig.queue.concurrency,
  }
);

emailWorker.on('completed', (job) => {
  console.log(\`Email sent: \${job.id}\`);
});

emailWorker.on('failed', (job, error) => {
  console.error(\`Email failed: \${job?.id}\`, error);
});

/**
 * Close worker
 */
export async function closeEmailWorker(): Promise<void> {
  await emailWorker.close();
}
`;
        return {
            path: path.join(outputDirectory, 'api/src/workers/email-worker.ts'),
            content,
        };
    }
    generateEmailTracking(_email, outputDirectory) {
        const content = `/**
 * Email Tracking
 * Generated by Bangstack
 */

export interface EmailTrackingData {
  messageId: string;
  to: string | string[];
  subject: string;
  template?: string;
  sentAt?: Date;
}

export interface EmailEvent {
  messageId: string;
  event: 'opened' | 'clicked' | 'bounced' | 'complained';
  timestamp: Date;
  metadata?: Record<string, any>;
}

/**
 * Track email
 */
export async function trackEmail(data: EmailTrackingData): Promise<void> {
  // Store email tracking data in database
  console.log('Tracking email:', data);

  // TODO: Implement database storage
}

/**
 * Record email event
 */
export async function recordEmailEvent(event: EmailEvent): Promise<void> {
  // Store email event in database
  console.log('Recording email event:', event);

  // TODO: Implement database storage
}

/**
 * Get email tracking data
 */
export async function getEmailTracking(messageId: string): Promise<EmailTrackingData | null> {
  // Retrieve from database
  console.log('Getting email tracking:', messageId);

  // TODO: Implement database retrieval
  return null;
}
`;
        return {
            path: path.join(outputDirectory, 'api/src/services/email-tracking.ts'),
            content,
        };
    }
    generateUnsubscribeHandler(_email, outputDirectory) {
        const content = `/**
 * Unsubscribe Handler
 * Generated by Bangstack
 */

import { Request, Response } from 'express';

/**
 * Handle unsubscribe request
 */
export async function handleUnsubscribe(req: Request, res: Response): Promise<void> {
  const { email, token } = req.query;

  if (!email || !token) {
    res.status(400).json({ error: 'Missing email or token' });
    return;
  }

  // Verify token
  // TODO: Implement token verification

  // Update user preferences
  // TODO: Update database

  res.json({ success: true, message: 'Successfully unsubscribed' });
}

/**
 * Generate unsubscribe link
 */
export function generateUnsubscribeLink(email: string): string {
  // Generate token
  // TODO: Implement token generation
  const token = 'example-token';

  return \`\${process.env.APP_URL}/unsubscribe?email=\${encodeURIComponent(email)}&token=\${token}\`;
}
`;
        return {
            path: path.join(outputDirectory, 'api/src/handlers/unsubscribe-handler.ts'),
            content,
        };
    }
    generateEmailTesting(_email, outputDirectory) {
        const content = `/**
 * Email Testing Utilities
 * Generated by Bangstack
 */

import { emailService } from '../services/email-service';

/**
 * Test email delivery
 */
export async function testEmailDelivery(): Promise<boolean> {
  try {
    const result = await emailService.send({
      to: process.env.TEST_EMAIL || 'test@example.com',
      subject: 'Test Email',
      html: '<p>This is a test email</p>',
      text: 'This is a test email',
    });

    return result.success;
  } catch (error) {
    console.error('Email test failed:', error);
    return false;
  }
}

/**
 * Mock email service for testing
 */
export class MockEmailService {
  private sentEmails: any[] = [];

  async send(data: any): Promise<{ success: boolean; messageId: string }> {
    this.sentEmails.push(data);
    return { success: true, messageId: 'mock-id-' + Date.now() };
  }

  getSentEmails(): any[] {
    return this.sentEmails;
  }

  clearSentEmails(): void {
    this.sentEmails = [];
  }
}
`;
        return {
            path: path.join(outputDirectory, 'api/src/utils/email-testing.ts'),
            content,
        };
    }
}
exports.EnhancedEmailGenerator = EnhancedEmailGenerator;
exports.enhancedEmailGenerator = new EnhancedEmailGenerator();
//# sourceMappingURL=enhanced-email-generator.js.map