const { faqModel , faqSection} = require("../../models/home/faqModel");

const faqController = {
 create: async (req, res) => {
  try {
    const { question, answer } = req.body;

    const data = {
      question: question?.trim(),
      answer: answer?.trim(),
      pages: req.body.pages ? JSON.parse(req.body.pages) : [],
      show_on_home: req.body.show_on_home
    };

    const result = await faqSection.create(data);

    if (result?.error) {
      return res.status(400).json({ success: false, message: result.error });
    }

    res.status(201).json({
      success: true,
      message: "FAQ created successfully!",
      data: result,
    });
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
},

  getAll: async (req, res) => {
    try {
      const result = await faqSection.getAll();
      if (!result.length) {
        return res.status(404).json({ success: false, message: "No Content found." });
      }
      res.status(200).json({ success: true, data: result });
    } catch (err) {
      res.status(500).json({ success: false, message: err.message });
    }
  },

  getSingle: async (req, res) => {
    try {
      const entry = await faqSection.getSingle(req.params.id);
      if (!entry) {
        return res.status(404).json({ success: false, message: "Content not found." });
      }
      res.status(200).json({ success: true, data: entry });
    } catch (err) {
      res.status(500).json({ success: false, message: err.message });
    }
  },

  update: async (req, res) => {
    try {
    const { question, answer } = req.body;

      const data = {
        question: question?.trim(),
        answer: answer?.trim(),
        pages: req.body.pages ? JSON.parse(req.body.pages) : [],
        show_on_home: req.body.show_on_home
      };
      const updated = await faqSection.update(req.params.id, data);
      if (!updated) {
        return res.status(404).json({ success: false, message: "Content not found." });
      }

      res.status(200).json({ success: true, message: "Content updated!", data: updated });
    } catch (err) {
      res.status(500).json({ success: false, message: err.message });
    }
  },

  delete: async (req, res) => {
    try {
      const deleted = await faqSection.delete(req.params.id);
      if (!deleted) {
        return res.status(404).json({ success: false, message: "Content not found." });
      }
      res.status(200).json({ success: true, ...deleted });
    } catch (err) {
      res.status(500).json({ success: false, message: err.message });
    }
  },
};

module.exports = faqController;
