const { splitSite } = require("../middlewares");
const db = require("../models");
const VehicleRepair = db.vehicle_repair;

exports.createVehicleRepair = (req, res) => {
  if (!req.body.part_name && !req.body.repair_description) {
    res.status(400).send({ message: "Part name or description is required." });
    return;
  }

	const site = splitSite.findSiteNumber(req);

	const vehicleRepair = new VehicleRepair({
		repair_date: req.body.repair_date,
		site,
		repair_description: req.body.repair_description || req.body.part_name || '',
		part_name: req.body.part_name || '',
		part_name_other: req.body.part_name_other || '',
		mileage_at_replacement: req.body.mileage_at_replacement || '',
		quantity: req.body.quantity || '',
		repair_price: req.body.repair_price || '',
		repair_location: req.body.repair_location || '',
		next_replacement_reminder: req.body.next_replacement_reminder || '',
		vehicle: req.body.vehicle,
		create_date: new Date()
	});

	vehicleRepair.save(vehicleRepair).then(data => res.send(data)).catch(err => {
		res.status(500).send({
			message: err.message || "Some error occurred while creating the Vehicle Repair Record."
		})
	})
}

exports.getAllVehicleRepairs = (req, res) => {
  var condition = {};
	const vehicle = req.query.vehicle;
  condition = splitSite.splitSiteGet(req, condition);
	condition.vehicle = vehicle;
  VehicleRepair.find(condition).sort({ create_date: -1 })
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving Vehicle Repair Records."
      });
    });
}

exports.updateVehicleRepair = (req, res) => {
  const id = req.params.id;
  VehicleRepair.findByIdAndUpdate(id, req.body, { new: true })
    .then(data => {
      if (!data) {
        res.status(404).send({ message: `Cannot update Vehicle Repair Record with id=${id}.` });
      } else {
        res.send(data);
      }
    })
    .catch(err => {
      res.status(500).send({
        message: err.message || "Could not update Vehicle Repair Record."
      });
    });
}

exports.deleteVehicleRepair = (req, res) => {
  const id = req.params.id;
  VehicleRepair.findByIdAndDelete(id)
    .then(data => {
      if (!data) {
        res.status(404).send({ message: `Cannot delete Vehicle Repair Record with id=${id}.` });
      } else {
        res.send({ message: "Vehicle Repair Record was deleted successfully!" });
      }
    })
    .catch(err => {
      res.status(500).send({
        message: err.message || "Could not delete Vehicle Repair Record."
      });
    });
};