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());

// Routes
app.get("/recipes", (req, res) => res.json(recipes));

app.get("/recipes/:id", (req, res) => {
  const recipe = recipes.find(r => r.id === req.params.id);
  recipe ? res.json(recipe) : res.status(404).send("Recipe not found");
});

app.post("/recipes", (req, res) => {
  const newRecipe: Recipe = { id: uuidv4(), ...req.body };
  recipes.push(newRecipe);
  res.status(201).json(newRecipe);
});

app.put("/recipes/:id", (req, res) => {
  const index = recipes.findIndex(r => r.id === req.params.id);
  if (index === -1) return res.status(404).send("Recipe not found");
  recipes[index] = { ...recipes[index], ...req.body };
  res.json(recipes[index]);
});

app.delete("/recipes/:id", (req, res) => {
  recipes = recipes.filter(r => r.id !== req.params.id);
  res.status(204).send();
});

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

