import express from "express";
import cors from "cors";
import { v4 as uuidv4 } from "uuid";

import { recipes } from "./mock_data/recipes"
import { Recipe } from "./types/recipe"


const app = express();
app.use(cors());
app.use(express.json());

let recipeList = recipes;
// Routes
/**
 * Load recipe list 
 * allows for filtering the list based on the recipes title using the query paramter search
 */
app.get("/recipe", (req, res) => {
  // extract search string from query parameters, convert to lower case for case insensitive search
  let searchString : string  = req.query.search ? req.query.search.toString().toLowerCase() : "";
  console.log("searchString", searchString)
  let resultList : Recipe[] = []
  if(searchString && searchString !== ""){
    // if theres a search string filter recipe list based on title
    // convert title to lower case in order to allow for case insensitive filtering
    resultList = recipeList.filter(recipe => recipe.title.toLowerCase().includes(searchString));
  } else {
    // if there is no search string simply return the entire list
    resultList = recipeList;
  }
  res.json(resultList)
});

/**
 * Load a single recipe by its id
 */
app.get("/recipe/:id", (req, res) => {
  let recipeId : string = req.params.id;
  const recipe = recipeList.find(r => r.id === recipeId);
  recipe ? res.json(recipe) : res.status(404).send("Recipe not found");
});

/**
 * Create a new recipe
 */
app.post("/recipe", (req, res) => {
  const newRecipe: Recipe = { id: uuidv4(), ...req.body };
  recipeList.push(newRecipe);
  res.status(201).json(newRecipe);
});

/**
 * Save an existing recipe
 */
app.put("/recipe/:id", (req, res) => {
  let recipeId : string = req.params.id;
  const index = recipeList.findIndex(r => r.id === recipeId);
  if (index === -1) {
    return res.status(404).send("Recipe not found");
  }
  recipeList[index] = { ...recipeList[index], ...req.body };
  res.json(recipeList[index]);
});

/**
 * Delete a recipe by id
 */
app.delete("/recipe/:id", (req, res) => {
  recipeList = recipeList.filter(r => r.id !== req.params.id);
  res.status(204).send();
});

app.listen(4000, () => console.log("Server running on http://localhost:4000"));

