import fetch from "node-fetch";
import dotenv from "dotenv";

dotenv.config(); // load .env variables

interface SendEmailOptions {
  to: { email: string; name?: string }[];
  subject: string;
  htmlContent: string;
  replyTo?: { email: string; name?: string }; // 👈 optional replyTo
}

const BREVO_API_URL = "https://api.brevo.com/v3/smtp/email";

const SENDER = {
  email: process.env.FROM_EMAIL!,
  name: "Humanizar-Texto IA",
};

export async function sendEmail({
  to,
  subject,
  htmlContent,
  replyTo,
}: SendEmailOptions) {
  try {
    const body: any = {
      sender: SENDER,
      to,
      subject,
      htmlContent,
    };

    if (replyTo) {
      body.replyTo = replyTo; // 👈 only include if provided
    }

    const response = await fetch(BREVO_API_URL, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "api-key": process.env.BREVO_API_KEY!,
      },
      body: JSON.stringify(body),
    });

    if (!response.ok) {
      const err = await response.text();
      console.error("Brevo API error:", err);
      throw new Error("Email API request failed");
    }

    console.log(
      `📧 Email sent successfully to: ${to.map((t) => t.email).join(", ")}`
    );
  } catch (error) {
    console.error("sendEmail error:", error);
    throw error;
  }
}
