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

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

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

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

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

// @desc    Create new return
// @route   POST /api/v1/returns
// @access  Private/Admin
exports.createReturn = asyncHandler(async (req, res, next) => {
  const returnItem = await Return.create(req.body);

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

// @desc    Update return
// @route   PUT /api/v1/returns/:id
// @access  Private/Admin
exports.updateReturn = asyncHandler(async (req, res, next) => {
  let returnItem = await Return.findById(req.params.id);

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

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

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

// @desc    Delete return
// @route   DELETE /api/v1/returns/:id
// @access  Private/Admin
exports.deleteReturn = asyncHandler(async (req, res, next) => {
  const returnItem = await Return.findById(req.params.id);

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

  await returnItem.remove();

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