const requestDbService = require("../services/requestDbService");
const nodemailer = require("nodemailer");
const getAllRequests = async (req, res) => {
  try {
    const data = await requestDbService.getAllRequests();
    res.status(201).json(data);
  } catch (err) {
    res.status(500).json({
      Status: "Something went wrong when fetching details!",
      error: err.message,
    });
  }
};

const getActiveRequests = async (req, res) => {
  try {
    const { lang } = req.params;

    const data = await requestDbService.getActiveRequests(lang);
    res.status(201).json(data);
  } catch (err) {
    res.status(500).json({
      Status: "Something went wrong when fetching details!",
      error: err.message,
    });
  }
};

const addReq = async (req, res) => {
  try {
    const { Name, Rating, Feedback } = req.body;

    await requestDbService.addReq(Name, Rating, Feedback);
    const transporter = nodemailer.createTransport({
      host: "premium54.web-hosting.com",
      port: 465,
      secure: true,
      auth: {
        user: "newsletter@gammatourz.com",
        pass: ",LAOn}D@F-[f",
      },
    });

    const mailOptions = {
      from: "Gamma Tourz <newsletter@gammatourz.com>",
      to: "inquiries@gammatourz.com",
      subject: "New Feedback Received!",
      text: `You have received a new Feedback:\n\nName: ${Name}\nRating: ${Rating} \nFeedback: ${Feedback}`,
    };

    await transporter.sendMail(mailOptions);

    res.status(201).json({ message: "request adding completed!" });
  } catch (err) {
    console.log(err);
    res.status(500).json({
      Status: "Something went wrong when adding details!",
      error: err.message,
    });
  }
};

const deleteReq = async (req, res) => {
  try {
    const { idRequests } = req.params;
    await requestDbService.deleteReq(idRequests);
    res.status(201).json({ success: true, message: "Deletion completed!" });
  } catch (err) {
    console.log(err);
    res.status(500).json({
      Status: "Something went wrong when fetching details!",
      error: err.message,
    });
  }
};

const getByid = async (req, res) => {
  try {
    const { idRequests } = req.params;
    const data = await requestDbService.getByid(idRequests);
    res.status(201).json(data);
  } catch (err) {
    res.status(500).json({
      Status: "Something went wrong when fetching details!",
      error: err.message,
    });
  }
};

const changeStatus = async (req, res) => {
  try {
    const { idRequests } = req.params;
    await requestDbService.changeStatus(idRequests);
    res
      .status(201)
      .json({ success: true, message: "Status changed successfully!" });
  } catch (err) {
    res.status(500).json({
      Status: "Something went wrong when fetching details!",
      error: err.message,
    });
  }
};
module.exports = {
  getAllRequests,
  addReq,
  deleteReq,
  getByid,
  changeStatus,
  getActiveRequests,
};
