// app/actions/sendEmail.js
"use server";
import nodemailer from "nodemailer";

export async function sendEmail(formData) {
  const transporter = nodemailer.createTransport({
    service: "Gmail",
    auth: {
      user: process.env.EMAIL_USER,
      pass: process.env.EMAIL_PASSWORD,
    },
  });

  // Extract form data values
  const attachment = formData.get("attachment"); // Get attachment from formData
  const isWarranty = formData.has("warranty_products");
  const subject = isWarranty ? "New Warranty Request" : "New Business Inquiry"; // Define subject

  // Validate file if present
  if (isWarranty && attachment && attachment.size > 0) {
    const validTypes = ["image/jpeg", "image/png"];
    const maxSize = 5 * 1024 * 1024;

    if (!validTypes.includes(attachment.type)) {
      return {error: "Invalid file type. Only JPG/PNG allowed"};
    }

    if (attachment.size > maxSize) {
      return {error: "File size exceeds 5MB limit"};
    }
  }

  // Determine email content based on form type
  const html = isWarranty
    ? `
      <h1>New Warranty Request</h1>
      <p><strong>Service Type:</strong> ${formData.get("warranty_services")}</p>
      <p><strong>Product:</strong> ${formData.get("warranty_products")}</p>
      <p><strong>Name:</strong> ${formData.get("warranty_name")}</p>
      <p><strong>Email:</strong> ${formData.get("warranty_email")}</p>
      <p><strong>Phone:</strong> ${formData.get("warranty_phone")}</p>
    `
    : `
      <h1>New Business Inquiry</h1>
      <p><strong>Name:</strong> ${formData.get("business_name")}</p>
      <p><strong>Company:</strong> ${formData.get("business_company")}</p>
      <p><strong>Email:</strong> ${formData.get("business_email")}</p>
      <p><strong>Phone:</strong> ${formData.get("business_phone")}</p>
      <p><strong>Services Needed:</strong> ${formData.get("business_services")}</p>
      <p><strong>Quantity:</strong> ${formData.get("business_quantity")}</p>
      <p><strong>Contact Preference:</strong> ${formData.get("business_contacted")}</p>
    `;

  const mailOptions = {
    from: process.env.EMAIL_USER,
    to: process.env.RECEIVING_EMAIL,
    subject,
    html,
    attachments:
      attachment && attachment.size > 0
        ? [
            {
              filename: attachment.name,
              content: Buffer.from(await attachment.arrayBuffer()),
            },
          ]
        : [],
  };

  try {
    await transporter.sendMail(mailOptions);
    return {success: true};
  } catch (error) {
    console.error("Email send error:", error);
    return {error: "Failed to send message. Please try again later."};
  }
}
