const EmailClient = require("../core/EmailClient");
const TemplateManager = require("../core/TemplateManager");
const logger = require("../../../utils/logger");

/**
 * AlphaInvitationEmailService handles alpha program invitation emails
 * This service is responsible for:
 * - Sending alpha access invitation codes to new testers
 */
class AlphaInvitationEmailService {
  constructor() {
    this.emailClient = new EmailClient();
    this.templateManager = new TemplateManager();
    this.initialized = false;
  }

  /**
   * Initialize the alpha invitation email service
   * @returns {Promise<void>}
   */
  async initialize() {
    if (this.initialized) return;

    await Promise.all([
      this.emailClient.initialize(),
      this.templateManager.initialize(),
    ]);

    this.initialized = true;
    logger.info("Alpha Invitation Email Service initialized successfully");
  }

  /**
   * Send alpha invitation email
   * @param {string} email - Recipient's email address
   * @param {string} code - Alpha access code
   * @returns {Promise<{success: boolean, messageId?: string, error?: string}>}
   */
  async sendAlphaInvitation(email, code) {
    if (!this.initialized) {
      await this.initialize();
    }

    try {
      const frontendUrl = process.env.FRONTEND_URL || "http://localhost:3000";

      const variables = {
        code: code,
        email: email,
        frontendUrl: frontendUrl,
        title: "Welcome to Alpha Testing!",
        message: `You've been invited to join our exclusive alpha testing program. Use the code <strong>${code}</strong> to unlock access and be among the first to experience our platform.`,
      };

      const htmlContent = await this.templateManager.renderTemplate(
        "alphaInvitationToUser",
        variables
      );

      return await this.emailClient.sendEmail(
        email,
        "Your Alpha Access Code - Village Share",
        htmlContent
      );
    } catch (error) {
      logger.error("Failed to send alpha invitation email", { error });
      return { success: false, error: error.message };
    }
  }
}

module.exports = AlphaInvitationEmailService;
