const db = require("../db/db");
const { translateText } = require("../utils/translator");
// Add blog category
const add = async (Name) => {
  const [Name_fr, Name_es, Name_gr] = await Promise.all([
    translateText(Name, "fr"),
    translateText(Name, "es"),
    translateText(Name, "de"),
  ]);
  const sql = `INSERT INTO blog_category (Name,Name_fr,Name_es,Name_gr) VALUES (?,?,?,?)`;
  return new Promise((resolve, reject) => {
    db.query(sql, [Name, Name_fr, Name_es, Name_gr], (err, results) => {
      if (err) reject(err);
      else resolve(results);
    });
  });
};

// Delete blog category by ID
const remove = (idBlogCategory) => {
  const sql = `DELETE FROM blog_category WHERE idBlogCategory = ?`;
  return new Promise((resolve, reject) => {
    db.query(sql, [idBlogCategory], (err, results) => {
      if (err) reject(err);
      else resolve(results);
    });
  });
};

// Optional: Get all blog categories
const getAll = () => {
  const sql = `SELECT * FROM blog_category`;
  return new Promise((resolve, reject) => {
    db.query(sql, (err, results) => {
      if (err) reject(err);
      else resolve(results);
    });
  });
};

const update = async (idBlogCategory, Name) => {
  const [Name_fr, Name_es, Name_gr] = await Promise.all([
    translateText(Name, "fr"),
    translateText(Name, "es"),
    translateText(Name, "de"),
  ]);

  const sql = `
    UPDATE blog_category 
    SET Name = ?, Name_fr = ?, Name_es = ?, Name_gr = ?
    WHERE idBlogCategory = ?
  `;

  return new Promise((resolve, reject) => {
    db.query(
      sql,
      [Name, Name_fr, Name_es, Name_gr, idBlogCategory],
      (err, results) => {
        if (err) reject(err);
        else resolve(results);
      }
    );
  });
};

const getbylang = (lang) => {
  let nameField = "Name";

  if (["fr", "es", "gr"].includes(lang)) {
    nameField = `Name_${lang}`;
  }
  const sql = `SELECT COALESCE(${nameField}) AS Name,idBlogCategory FROM blog_category`;
  return new Promise((resolve, reject) => {
    db.query(sql, (err, results) => {
      if (err) {
        reject(err);
      } else {
        resolve(results);
      }
    });
  });
};

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