const router = require("express").Router();
const Salary = require("../models/Salary");

// CREATE + UPDATE LOGIC REUSED
const calc = (b) => ({
  ...b,
  netSalary: b.grossSalary - b.totalDeduction
});

// CREATE
router.post("/", async (req, res) => {
  res.json(await Salary.create(calc(req.body)));
});

// READ
router.get("/", async (req, res) => {
  res.json(await Salary.find());
});

router.get("/:id", async (req, res) => {
  res.json(await Salary.findById(req.params.id));
});

// UPDATE
router.put("/:id", async (req, res) => {
  res.json(await Salary.findByIdAndUpdate(
    req.params.id,
    calc(req.body),
    { new: true }
  ));
});

// DELETE
router.delete("/:id", async (req, res) => {
  res.json(await Salary.findByIdAndDelete(req.params.id));
});

module.exports = router;