//The URLs at which the application can be accessed, mappinng them to corresponding controller functions => defining the structure of the API

const express = require("express");
const router = express.Router();
const multer = require("multer");
const Tesseract = require("tesseract");
const recipeController = require("../controllers/recipeController");

//multer for file storage
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "uploads/"); //have to make sure this dir exists
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + "-" + file.originalname);
  },
});

const upload = multer({ storage: storage });

//My routes
router.get("/", recipeController.getAllRecipes);
router.get("/:id", recipeController.getRecipe);
router.post("/", recipeController.createRecipe);
router.put("/:id", recipeController.updateRecipe);
router.delete("/:id", recipeController.deleteRecipe);

//Route for image upload and OCR
router.post("/upload", upload.single("image"), (req, res) => {
  Tesseract.recognize(req.file.path, "eng", {
    logger: (m) => console.log(m),
  })
    .then(({ data: { text } }) => {
      const crNumber = extractCrNumberFromText(text);
      const recipeData = { ...req.body, crNumber: crNumber };

      //calling controller function to save recipe data with CR number
      // Now call the controller function to save the recipe data along with the CR number
      Recipe.createRecipeWithOCR(
        recipeData,
        (result) => {
          // Send response back
          res
            .status(201)
            .json({ message: "Recipe and CR number saved", data: result });
        },
        (error) => {
          res.status(500).json({ error: error.message });
        }
      );
    })
    .catch((error) => {
      console.error(error);
      res.status(500).json({ error: "Failed to process image" });
    });
});

function extractCrNumberFromText(text) {}

module.exports = router;
