const db = require("../db/db");
const { translateText } = require("../utils/translator");

const add = async (Question, Answer) => {
  const [
    Question_fr,
    Question_es,
    Question_gr,
    Answer_fr,
    Answer_es,
    Answer_gr,
  ] = await Promise.all([
    translateText(Question, "fr"),
    translateText(Question, "es"),
    translateText(Question, "de"),
    translateText(Answer, "fr"),
    translateText(Answer, "es"),
    translateText(Answer, "de"),
  ]);

  const sql = `INSERT INTO qa (Question, Answer,Question_fr,Question_es,Question_gr,Answer_fr,Answer_es,Answer_gr) VALUES (?,?,?,?,?,?,?,?)`;
  return new Promise((resolve, reject) => {
    db.query(
      sql,
      [
        Question,
        Answer,
        Question_fr,
        Question_es,
        Question_gr,
        Answer_fr,
        Answer_es,
        Answer_gr,
      ],
      (err, results) => {
        if (err) {
          reject(err);
        } else {
          resolve(results);
        }
      }
    );
  });
};

const getAll = () => {
  const sql = `SELECT * FROM qa`;
  return new Promise((resolve, reject) => {
    db.query(sql, (err, results) => {
      if (err) {
        reject(err);
      } else {
        resolve(results);
      }
    });
  });
};

const update = async (idQa, Question, Answer) => {
  const [
    Question_fr,
    Question_es,
    Question_gr,
    Answer_fr,
    Answer_es,
    Answer_gr,
  ] = await Promise.all([
    translateText(Question, "fr"),
    translateText(Question, "es"),
    translateText(Question, "de"),
    translateText(Answer, "fr"),
    translateText(Answer, "es"),
    translateText(Answer, "de"),
  ]);

  const sql = `UPDATE qa SET Question = ?, Answer = ?,Question_fr = ?,Question_es= ?,Question_gr = ?,Answer_fr = ?,Answer_es = ?,Answer_gr = ? WHERE idQa = ?`;
  return new Promise((resolve, reject) => {
    db.query(
      sql,
      [
        Question,
        Answer,
        Question_fr,
        Question_es,
        Question_gr,
        Answer_fr,
        Answer_es,
        Answer_gr,
        idQa,
      ],
      (err, results) => {
        if (err) reject(err);
        else resolve(results);
      }
    );
  });
};

const remove = (idQa) => {
  const sql = `DELETE FROM qa WHERE idQa = ?`;
  return new Promise((resolve, reject) => {
    db.query(sql, [idQa], (err, results) => {
      if (err) reject(err);
      else resolve(results);
    });
  });
};

const getByLang = (lang) => {
  let answerField = "Answer";
  let questionField = "Question";

  if (["fr", "es", "gr"].includes(lang)) {
    answerField = `Answer_${lang}`;
    questionField = `Question_${lang}`;
  }

  const sql = `SELECT  idQa,COALESCE(${questionField}) AS Question,COALESCE(${answerField}) AS Answer FROM qa`;
  return new Promise((resolve, reject) => {
    db.query(sql, (err, results) => {
      if (err) {
        reject(err);
      } else {
        resolve(results);
      }
    });
  });
};

module.exports = {
  add,
  getAll,
  update,
  remove,
  getByLang,
};
