const express = require("express");
const router = express.Router();
const db = require("../models");
const EmailQueue = db.email_queue;

// GET /api/v1/email_queue (get all)
router.get("/", async (req, res) => {
  try {
    const queues = await EmailQueue.findAll();
    res.json({ success: true, data: queues });
  } catch (err) {
    res.status(500).json({ success: false, error: err.message });
  }
});

// GET /api/v1/email_queue/:id (get one)
router.get("/:id", async (req, res) => {
  try {
    const queue = await EmailQueue.findByPk(req.params.id);
    if (!queue)
      return res
        .status(404)
        .json({ success: false, error: "Email queue not found" });
    res.json({ success: true, data: queue });
  } catch (err) {
    res.status(500).json({ success: false, error: err.message });
  }
});

// POST /api/v1/email_queue (add one)
router.post("/", async (req, res) => {
  try {
    const queue = await EmailQueue.create(req.body);
    res.status(201).json({ success: true, data: queue });
  } catch (err) {
    res.status(400).json({ success: false, error: err.message });
  }
});

// PUT /api/v1/email_queue/:id (update one)
router.put("/:id", async (req, res) => {
  try {
    const [updated] = await EmailQueue.update(req.body, {
      where: { id: req.params.id },
    });
    if (!updated)
      return res
        .status(404)
        .json({ success: false, error: "Email queue not found" });
    const queue = await EmailQueue.findByPk(req.params.id);
    res.json({ success: true, data: queue });
  } catch (err) {
    res.status(400).json({ success: false, error: err.message });
  }
});

// DELETE /api/v1/email_queue/:id (delete one)
router.delete("/:id", async (req, res) => {
  try {
    const deleted = await EmailQueue.destroy({ where: { id: req.params.id } });
    if (!deleted)
      return res
        .status(404)
        .json({ success: false, error: "Email queue not found" });
    res.json({ success: true, data: "Email queue deleted" });
  } catch (err) {
    res.status(500).json({ success: false, error: err.message });
  }
});

module.exports = router;
