const express = require('express');
const router = express.Router();
const {
	getAllProducts,
	getProduct,
	addToCart,
	getCartItems,
	updateCartItem,
	removeFromCart,
	purchase,
	purchases,
	payPurchase,
} = require('../../controllers/members/products');
const { memberAuth, validation } = require('../../middlewares');
const { body } = require('express-validator');

router.post(
	'/purchase',
	memberAuth,
	[
		body('products').isArray({ min: 1 }).withMessage('Products must be a non-empty array'),
		body('products.*.id').notEmpty().withMessage('Product id is required'),
		body('products.*.quantity').isInt({ min: 1 }).withMessage('Quantity must be at least 1'),
		body('products.*.color').optional({ nullable: true }).isString().withMessage('Color must be a string'),
		body('products.*.size').optional({ nullable: true }).isString().withMessage('Size must be a string'),
		validation,
	],
	purchase,
);

router.get('/purchase', memberAuth, purchases);
router.post('/purchase/pay', payPurchase);

router.post(
	'/cart',
	memberAuth,
	[body('productId').notEmpty(), body('quantity').isInt({ min: 1 }), validation],
	addToCart,
);
router.get('/cart', memberAuth, getCartItems);
router.patch('/cart', memberAuth, updateCartItem);
router.delete('/cart/:id', memberAuth, removeFromCart);

router.get('/', getAllProducts);
router.get('/:id', getProduct);

module.exports = router;
