const db = require("../models");
const nodemailer = require("nodemailer");
require("dotenv").config();

(async () => {
  try {
    const EmailQueue = db.email_queue;
    const Email = db.email;
    const User = db.user;
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const tomorrow = new Date(today);
    tomorrow.setDate(today.getDate() + 1);

    // 1. Get all email_queue entries for today and not sent
    const queues = await EmailQueue.findAll({
      where: {
        send_at: { $gte: today, $lt: tomorrow },
        status: 0,
      },
    });
    if (!queues.length) {
      console.log("No emails to send today.");
      return;
    }

    // 2. Setup nodemailer with Mailtrap
    const transporter = nodemailer.createTransport({
      host: process.env.MAILTRAP_HOST,
      port: process.env.MAILTRAP_PORT,
      auth: {
        user: process.env.MAILTRAP_USER,
        pass: process.env.MAILTRAP_PASS,
      },
    });

    let sentCount = 0;
    for (const queue of queues) {
      // 3. Get user and email
      const user = await User.findByPk(queue.user_id);
      const email = await Email.findByPk(queue.email_id);
      if (!user || !email) continue;
      // 4. Replace template
      let body = email.body
        .replace(/\{\{\{NAME\}\}\}/g, user.name)
        .replace(/\{\{\{EMAIL\}\}\}/g, user.email);
      // 5. Send email
      await transporter.sendMail({
        from: "noreply@example.com",
        to: user.email,
        subject: email.subject,
        html: body,
      });
      // 6. Mark as sent
      queue.status = 1;
      queue.updated_at = new Date();
      await queue.save();
      sentCount++;
    }
    console.log(`Sent ${sentCount} emails.`);
    process.exit(0);
  } catch (err) {
    console.error("Error in email_sending cronjob:", err);
    process.exit(1);
  }
})();
