import nodemailer from "nodemailer";
import { NextResponse } from "next/server";
import { emailFrom, emailHost, emailPassword, emailPort, emailSecure, emailUserName } from "@/app/utils/variables";

export async function POST(req) {
  try {
    const formData = await req.formData();
    const to = formData.get("to");
    const subject = formData.get("subject");
    const cc = formData.get("cc") || "";
    const message = formData.get("message");

    if (!to || !subject || !message) {
      return NextResponse.json({ error: "Missing required fields" }, { status: 400 });
    }

    const attachments = await Promise.all(
      formData.getAll("attachments").map(async (file) => ({
        filename: file.name,
        content: Buffer.from(await file.arrayBuffer()),
      }))
    );

    const transporter = nodemailer.createTransport({
      host: emailHost,
      port: emailPort,
      secure: emailSecure, // TLS
      auth: {
        user: emailUserName,
        pass: emailPassword, // App Password from Google
      },
    });

    await transporter.sendMail({
      from: emailFrom,
      to,
      cc,
      subject,
      html: message,
      text: message.replace(/<[^>]+>/g, ""),
      attachments,
    });

    return NextResponse.json({ success: true, message: "Email sent successfully" });
  } catch (err) {
    console.error("Email send error:", err);
    return NextResponse.json({ success: false, error: "Email sending failed" }, { status: 500 });
  }
}

