const express = require("express");
const nodemailer = require("nodemailer");
const fs = require("fs");
const multer = require("multer");
const router = express.Router();

// Multer setup remains intact

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "./"); // Customize directory if needed
  },
  filename: function (req, file, cb) {
    cb(null, file.originalname);
  },
});
const upload = multer({ storage });

// Single transporter setup clearly moved to top (no duplication)
const transporter = nodemailer.createTransport({
  service: "gmail",
  auth: {
    user: "swdc.ate@gmail.com",
    pass: "umlc hbkr dpga iywd",
  },
  tls: { rejectUnauthorized: false },
  connectionTimeout: 60000,
  greetingTimeout: 60000,
  socketTimeout: 60000,
});

// Existing Excel route unchanged, except transporter removal
router.post("/excel", upload.single("file"), async (req, res) => {
  const { teacher, fileName, recipientEmail } = req.body;

  if (!teacher || !fileName || !recipientEmail || !req.file) {
    return res.status(400).json({ error: "Missing required fields or file" });
  }

  const mailOptions = {
    from: "SWDC Admin <swdc.ate@gmail.com>",
    to: recipientEmail,
    subject: `Examination Appointments for ${teacher}`,
    text: `Dear Sir/Madam,

Please find attached the Excel sheet regarding various appointments for the May-June 2024 Examination. Kindly find the tick mark (√) for the respective appointments.

Note: Kindly download the Excel sheet to view the hidden columns referring to the Scheme and other information.

If you have any queries, please contact the H.O.D or the Examination In-charge.

Your cooperation regarding the upcoming examination duties is highly solicited.`,
    attachments: [{ filename: fileName, path: req.file.path }],
  };

  try {
    await transporter.sendMail(mailOptions);
    transporter.close();

    // Delete the temporary file after sending the email
    fs.unlinkSync(req.file.path);
    res.status(200).json({ message: "Email sent successfully" });
  } catch (error) {
    console.error("Error sending email:", error);
    res.status(500).json({ error: "Failed to send email" });
  }
});

// Route to send emails with single PDF attachment remains intact
router.post("/pdf", upload.single("pdfFile"), async (req, res) => {
  const { fileName, recipientEmail, role, courseName } = req.body;

  if (!fileName || !recipientEmail || !role || !courseName || !req.file) {
    return res.status(400).json({ error: "Missing required fields or file" });
  }

  const mailOptions = {
    from: "SWDC Admin <swdc.ate@gmail.com>",
    to: recipientEmail,
    subject: `Appointment as ${role} - ${courseName}`,
    text: `Dear teacher,

You have been appointed as a ${role} for the course "${courseName}".
Please find your appointment letter attached.

If you have any queries, please contact the Examination In-charge.

Best regards,
Examination Department`,
    attachments: [{ filename: fileName, path: req.file.path }],
  };

  try {
    await transporter.sendMail(mailOptions);
    transporter.close();

    fs.unlinkSync(req.file.path);
    res.status(200).json({ message: "Email sent successfully" });
  } catch (error) {
    console.error("Error sending email:", error);
    res.status(500).json({ error: "Failed to send email" });
  }
});

// ✅ New route clearly added to handle multiple PDF attachments
// ✅ Correct and clean bulk-pdf route clearly stated
router.post("/bulk-pdf", upload.array("pdfFiles"), async (req, res) => {
  const { recipientEmail, facultyName, courseName } = req.body;

  if (!recipientEmail || !facultyName || !courseName || !req.files || req.files.length === 0) {
    return res.status(400).json({ error: "Missing required fields or files" });
  }

  const attachments = req.files.map((file) => ({
    filename: file.originalname,
    path: file.path,
  }));

  const mailOptions = {
    from: "SWDC Admin <swdc.ate@gmail.com>",
    to: recipientEmail,
    subject: `Appointment Letters - ${courseName}`,
    text: `Dear ${facultyName},

Please find your appointment letters attached.

If you have any queries, please contact the Examination In-charge.

Best regards,
Examination Department`,
    attachments,
  };

  try {
    await transporter.sendMail(mailOptions);
    transporter.close();

    // ✅ Ensure files are deleted after successful sending
    attachments.forEach((attachment) => {
      if (fs.existsSync(attachment.path)) {
        fs.unlinkSync(attachment.path);
      }
    });

    res.status(200).json({ message: "Bulk email sent successfully" });
  } catch (error) {
    console.error("Error sending bulk email (backend):", error);

    attachments.forEach((attachment) => {
      if (fs.existsSync(attachment.path)) {
        fs.unlinkSync(attachment.path);
      }
    });

    res.status(500).json({ error: "Failed to send bulk email", details: error.message });
  }
});


module.exports = router;
