export const updateProduct = async (req, res, next) => {
  const { color, size, discount } = req.body;
  let product = await Product.findById(req.params.id);

  if (!product) {
    return next(new ErrorHander('Product not found', 404));
  }

  // Images Start Here
  let images = [];

  if (typeof req.body.images === 'string') {
    images.push(req.body.images);
  } else {
    images = req.body.images;
  }

  if (images !== undefined) {
    // Deleting Images From Cloudinary
    for (let i = 0; i < product.images.length; i++) {
      await cloudinary.v2.uploader.destroy(product.images[i].public_id);
    }

    const imagesLinks = [];

    for (let i = 0; i < images.length; i++) {
      const result = await cloudinary.v2.uploader.upload(images[i], {
        folder: 'products',
      });

      imagesLinks.push({
        public_id: result.public_id,
        url: result.secure_url,
      });
    }

    req.body.images = imagesLinks;
  }

  if (!req.body.discount) {
    req.body.discount = 0;
  }

  // Discount calculate price on update product
  product.discount = discount || 0;
  const discountedPrice = product.calculateDiscountedPrice();
  req.body.discountedPrice = discountedPrice;

  product = await Product.findByIdAndUpdate(
    req.params.id,
    Object.assign(req.body, {
      color: JSON.parse(color),
      size: JSON.parse(size),
    }),
    {
      new: true,
      runValidators: true,
      useFindAndModify: false,
    }
  );

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