const fs = require("fs");
const path = require("path");

const questionsData = require("../data/questions.json");
const questionsFilePath = path.join(__dirname, "../data/questions.json");

const getAllQuestions = (req, res) => {
  fs.readFile(questionsFilePath, "utf8", (err, data) => {
    if (err) {
      res.status(500).send("Error reading file");
      return;
    }
    res.status(200).json(JSON.parse(data));
  });
};

const newQuestion = (req, res, next) => {
  const newQuestionText = req.body.question;
  if (newQuestionText) {
    fs.readFile(questionsFilePath, "utf8", (err, data) => {
      if (err) {
        return res.status(500).send("Error reading file");
      }
      let questionsData = JSON.parse(data);
      if (!questionsData.questions) {
        questionsData.questions = []; // Initialize if not present
      }

      // Check if the question already exists
      if (!questionsData.questions.includes(newQuestionText)) {
        questionsData.questions.push(newQuestionText);

        fs.writeFile(
          questionsFilePath,
          JSON.stringify(questionsData, null, 2),
          "utf8",
          (err) => {
            if (err) {
              return res.status(500).send("Error writing file");
            }
            res.status(200).send("Question added successfully");
          }
        );
      } else {
        res.status(200).send("Question already exists");
        next(); // or use status 200 if you prefer not to indicate an error
      }
    });
  } else {
    res.status(400).send("No question provided");
  }
};

module.exports = {
  getAllQuestions,
  newQuestion,
};
