const express = require("express");
const uuid = require("uuid");
const router = express.Router();
const items = require("../../items");

// Get All items
router.get("/", (req, res) => res.json(items));

// Get single item
router.get("/:id", (req, res) => {
  const found = items.some((item) => item.id === parseInt(req.params.id));
  // res.send(req.params.id);
  if (found) {
    res.json(items.filter((item) => item.id === parseInt(req.params.id)));
  } else {
    res.status(400).json({ msg: `item not found with id of ${req.params.id}` });
  }
});

// Create Item
router.post("/", (req, res) => {
  // res.send(req.body);

  const newItem = {
    id: uuid.v4(),
    name: req.body.name,
    email: req.body.email,
    status: "active",
  };

  if (!newItem.name || !newItem.email) {
    return res.status(400).json({ msg: "Please include name and email." });
  }

  items.push(newItem);

  res.json(items);
});

// Create Item
router.put("/:id", (req, res) => {
  const found = items.some((item) => item.id === parseInt(req.params.id));
  // res.send(req.params.id);
  if (found) {
    const updItem = req.body;
    items.forEach((item) => {
      if (item.id === parseInt(req.params.id)) {
        item.name = updItem.name ? updItem.name : item.name;
        item.email = updItem.email ? updItem.email : item.email;

        return res.json({ msg: "item updated", item });
      }
    });

    res.json(items.filter((item) => item.id === parseInt(req.params.id)));
  } else {
    res.status(400).json({ msg: `item not found with id of ${req.params.id}` });
  }
});

// Delete item
router.delete("/:id", (req, res) => {
  const found = items.some((item) => item.id === parseInt(req.params.id));
  // res.send(req.params.id);
  if (found) {
    res.json({
      msg: "Item deleted",
      items: items.filter((item) => item.id !== parseInt(req.params.id)),
    });
  } else {
    res.status(400).json({ msg: `item not found with id of ${req.params.id}` });
  }
});

module.exports = router;
