const express = require("express");
const nodemailer = require("nodemailer");

const router = express.Router();

router.post("/api/v1/contact", async (req, res) => {
  const { fullName, email, subject, message } = req.body;

  // Basic validation
  if (!fullName || !email || !subject || !message) {
    return res
      .status(400)
      .json({ success: false, message: "All fields are required." });
  }

  try {
    // Set up Nodemailer SMTP transporter
    const transporter = nodemailer.createTransport({
      host: process.env.EMAIL_HOST,
      port: parseInt(process.env.EMAIL_PORT, 10),
      secure: process.env.EMAIL_SECURE === "true", // true for port 465, false for 587
      auth: {
        user: process.env.EMAIL_USER,
        pass: process.env.EMAIL_PASS,
      },
      tls: {
        rejectUnauthorized: false, // Accept self-signed certificates (use only if needed)
      },

      logger: true, // Logs SMTP conversation
      debug: true, // Logs detailed debug info
    });

    // Email options
    const mailOptions = {
      from: `"Website Contact" <${process.env.EMAIL_USER}>`,
      to: process.env.EMAIL_RECEIVER,
      subject: `New Message from ${fullName} - ${subject}`,
      text: `You received a message from your website contact form:\n\nName: ${fullName}\nEmail: ${email}\nSubject: ${subject}\nMessage:\n${message}`,
    };

    // Send the email
    await transporter.sendMail(mailOptions);

    res.status(200).json({ message: "Message sent successfully!" });
  } catch (error) {
    console.error("Email sending failed:", error);
    res.status(500).json({ message: "Failed to send message." });
  }
});

module.exports = router;
