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


router.get("/compras", checkAuth, async (req, res) => {
    var compras;
  
    compras = await Compra.find({ user: req.userData._id }).sort({
      fecha: "desc",
    });
  
   return res.send(
        {
            status:"ok",
            data:compras

        }
    )
  });


  router.post("/compra", checkAuth, async (req, res) => {
    const { fecha, detalle, valor, metodopago, categoria } = req.body;
    const newCompra = new Compra({
      fecha,
      detalle,
      valor,
      metodopago,
      categoria,
    });

    console.log(newCompra)
    newCompra.user = req.userData._id;
    await newCompra.save();

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

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

    try{
      const userId = req.userData._id;
      const id = req.query.id;
      
      const resultado = await Compra.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;