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


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

        }
    )
  });


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

    var metodo = await Metodo.findOne({ name: name });
    if (metodo) {
      return res.status(500).json({ status: "fail", error: "Método de pago existente" });
      
    }

    const newMetodo = new Metodo({
      user,
      name,
      icon,
    });

    await newMetodo.save();

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

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

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