const router = require("express").Router();
const Categoria = require("../models/categoria");
const { checkAuth } = require("../middlewares/authentication");


router.get("/categoria", checkAuth, async (req, res) => {
    var categorias;
  
    categorias = await Categoria.find({ user: req.userData._id });
  
   return res.send(
        {
            status:"ok",
            data:categorias

        }
    )
  });


  router.post("/categoria", checkAuth, async (req, res) => {
    const {name, icon} = req.body;
    const user= req.userData._id;

    var categoria = await Categoria.findOne({ name: name });
    if (categoria) {
      return res.status(500).json({ status: "fail", error: "Categoria existente" });
      
    }

    const newCategoria = new Categoria({
      user,
      name,
      icon,
    });

    await newCategoria.save();

    res.json({
      status:"ok"
    })
  
   
  });

  router.delete("/categoria", checkAuth, async (req, res) => {

    try{
      const userId = req.userData._id;
      const id = req.query.id;
      
      const resultado = await Categoria.deleteOne({user:userId,_id:id});
    
      return res.json({status:"ok",data: resultado})
    
    }
    catch(error){
      console.log(error);
        return res.status(500).json({status:"fail",error:error})
    }
  });


  module.exports = router;