//intermediary layer between routes and model
//each func corresponds to operation that can be performed on resources, ie. fetching, adding etc. These will call the methods on the models tp interact ith the database and rhen format and send responses back to the client

const Recipe = require("../models/recipeModel");

exports.createRecipe = (req, res) => {
  const newRecipe = req.body;

  //use recipe model to create a recipe and send response:
  Recipe.createNew(newRecipe)
    .then((result) => {
      res.status(201).json({
        message: "Recipe created sucessfuly",
        recipeId: result.insertId,
        recipe: newRecipe,
      });
    })
    .catch((err) => {
      res.status(500).json({ error: err.message });
    });
};

//New one with scanned OCR number
exports.createRecipeWithOCR = (recipeData, successCallback, errorCallback) => {
  Recipe.createNew(recipeData)
    .then((result) => {
      successCallback(result);
    })
    .catch((err) => {
      errorCallback(err);
    });
};

exports.getAllRecipes = (req, res) => {
  //use recipe model to fetch all recipes and send response
  Recipe.findAll()
    .then((recipes) => {
      res.status(200).json(recipes);
    })
    .catch((err) => {
      res.status(500).json({ error: err.message });
    });
};

exports.getRecipe = (req, res) => {
  const { id } = req.params;
  // Use Recipe model to fetch a single recipe and send response

  Recipe.findById(id)
    .then((recipe) => {
      if (recipe) {
        res.status(200).json(recipe);
      } else {
        res.status(404).json({ message: "Recipe not found" });
      }
    })
    .catch((err) => {
      res.status(500).json({ error: err.message });
    });
};

exports.updateRecipe = (req, res) => {
  const { id } = req.params;
  const recipeUpdate = req.body;
  // Use Recipe model to update Recipe and send response

  Recipe.updateById(id, recipeUpdate)
    .then((result) => {
      if (result.affectedRows > 0) {
        res.status(200).json({ message: "Recipe updated succesfully" });
      } else {
        res.status(404).json({ message: "Recipe not found" });
      }
    })
    .catch((err) => {
      res.status(500).json({ error: err.message });
    });
};

exports.deleteRecipe = (req, res) => {
  const { id } = req.params;
  // Use Recipe model to delete an item by id and a response
  Recipe.deleteById(id)
    .then((result) => {
      if (result.affectedRows > 0) {
        res.status(200).json({ message: "Recipe deleted successfully" });
      } else {
        res.status(404).json({ message: "Recipe not found" });
      }
    })
    .catch((err) => {
      res.status(500).json({ error: err.message });
    });
};

// Make sure insertId and affectedRows are properties that your database driver actually returns in the result object
