const Refund = require('../models/Refund');
const asyncHandler = require('../middleware/async');

// @desc    Get all refunds
// @route   GET /api/v1/refunds
// @access  Private/Admin
exports.getAllRefunds = asyncHandler(async (req, res, next) => {
  res.status(200).json(res.advancedResults);
});

// @desc    Get single refund
// @route   GET /api/v1/refunds/:id
// @access  Private/Admin
exports.getRefundById = asyncHandler(async (req, res, next) => {
  const refund = await Refund.findById(req.params.id).populate('order', 'orderNumber').populate('customer', 'name');

  if (!refund) {
    return next(
      new ErrorResponse(`Refund not found with id of ${req.params.id}`, 404)
    );
  }

  res.status(200).json({ success: true, data: refund });
});

// @desc    Create new refund
// @route   POST /api/v1/refunds
// @access  Private/Admin
exports.createRefund = asyncHandler(async (req, res, next) => {
  const refund = await Refund.create(req.body);

  res.status(201).json({
    success: true,
    data: refund,
  });
});

// @desc    Update refund
// @route   PUT /api/v1/refunds/:id
// @access  Private/Admin
exports.updateRefund = asyncHandler(async (req, res, next) => {
  let refund = await Refund.findById(req.params.id);

  if (!refund) {
    return next(
      new ErrorResponse(`Refund not found with id of ${req.params.id}`, 404)
    );
  }

  refund = await Refund.findByIdAndUpdate(req.params.id, req.body, {
    new: true,
    runValidators: true,
  });

  res.status(200).json({ success: true, data: refund });
});

// @desc    Delete refund
// @route   DELETE /api/v1/refunds/:id
// @access  Private/Admin
exports.deleteRefund = asyncHandler(async (req, res, next) => {
  const refund = await Refund.findById(req.params.id);

  if (!refund) {
    return next(
      new ErrorResponse(`Refund not found with id of ${req.params.id}`, 404)
    );
  }

  await refund.remove();

  res.status(200).json({ success: true, data: {} });
});
