import Mailgun from "mailgun.js";
import formData from "form-data";
import mjml2html from "mjml";

const mailgun = new Mailgun(formData);

const API_KEY = process.env.MAILGUN_API_KEY || "";
const DOMAIN = process.env.MAILGUN_DOMAIN || "";
const API_URL = process.env.MAILGUN_API_URL || "https://api.mailgun.net";

// Initialize the Mailgun client
const mg = mailgun.client({
  username: "api",
  key: API_KEY,
  url: API_URL,
});

export interface SendEmailOptions {
  to: string | string[];
  subject: string;
  text: string;
  html?: string;
  mjml?: string; // Optional: If provided, this will be compiled to HTML and override the `html` field.
  from?: string; // Optional: If not provided, defaults to the Mailgun system domain
}

/**
 * Sends an email using the Mailgun API.
 * If `mjml` is provided, it compiles it to responsive HTML before sending.
 */
export async function sendEmail(options: SendEmailOptions) {
  // Use the provided from address, or fallback to a default on the live domain
  const fromAddress = options.from || `Vibn AI <mailgun@${DOMAIN}>`;

  // Format the 'to' address
  const toAddresses = Array.isArray(options.to)
    ? options.to.join(",")
    : options.to;

  // Process MJML if it exists
  let finalHtml = options.html;
  if (options.mjml) {
    try {
      const compiled = mjml2html(options.mjml, {
        validationLevel: "soft", // Warn on errors but try to compile anyway
        minify: true,
      });
      if (compiled.errors && compiled.errors.length > 0) {
        console.warn("[MJML Compiler Warnings]:", compiled.errors);
      }
      finalHtml = compiled.html;
    } catch (e) {
      console.error("[MJML Compiler Error]:", e);
      // Fallback to plain text if MJML fails catastrophically
      finalHtml = undefined;
    }
  }

  try {
    const response = await mg.messages.create(DOMAIN, {
      from: fromAddress,
      to: toAddresses,
      subject: options.subject,
      text: options.text,
      html: finalHtml,
    });

    return {
      success: true,
      id: response.id,
      message: response.message,
    };
  } catch (error: any) {
    console.error("[Mailgun Error]:", error);
    return {
      success: false,
      error: error.message || "Failed to send email via Mailgun",
      status: error.status,
    };
  }
}
