//representation of the data
//Handling the logic

const db = require("../database");

class Recipe {
  static createNew(recipeData) {
    return new Promise((resolve, reject) => {
      const { name, date, description, crNumber, status } = recipeData;
      db.query(
        "INSERT INTO recipes (name, date, description, crNumber, status) VALUES (?, ?, ?, ?, ?)",
        [name, date, description, crNumber, status],
        (err, result) => {
          if (err) {
            reject(err);
          }
          resolve(result);
        }
      );
    });
  }

  static findAll() {
    return new Promise((resolve, reject) => {
      db.query("SELECT * FROM recipes", (err, results) => {
        if (err) {
          return reject(err);
        }
        resolve(results);
      });
    });
  }

  static findById(id) {
    return new Promise((resolve, reject) => {
      db.query("SELECT * FROM recipes WHERE id = ?", [id], (err, results) => {
        if (err) {
          return reject(err);
        }
        //ids are unique so only one will be returned if found by id.
        resolve(results[0]);
      });
    });
  }

  static updateById(id, recipeData) {
    return new Promise((resolve, reject) => {
      const { name, date, description, crNumber, status } = recipeData;
      db.query(
        "UPDATE recipes SET name = ?, date = ?, description = ?, crNumber = ?, status = ? WHERE id = ?",
        [name, date, description, crNumber, status, id],
        (err, result) => {
          if (err) {
            return reject(err);
          }
          resolve(result);
        }
      );
    });
  }
  static deleteById(id) {
    return new Promise((resolve, reject) => {
      db.query("DELETE from recipes WHERE id = ?", [id], (err, result) => {
        if (err) {
          return reject(err);
        }
        resolve(result);
      });
    });
  }
}

module.exports = Recipe;
