const express = require('express');
const router = express.Router();
const returnController = require('../controllers/returnController');
const { authenticate } = require('../middleware/auth');
const { body, param, query } = require('express-validator');

// Validation middleware
const validateCreateReturn = [
  body('transactionId').notEmpty().withMessage('Transaction ID is required'),
  body('customerId').optional(),
  body('storeId').notEmpty().withMessage('Store ID is required'),
  body('registerId').notEmpty().withMessage('Register ID is required'),
  body('reason').notEmpty().withMessage('Return reason is required'),
  body('items').isArray({ min: 1 }).withMessage('At least one item is required'),
  body('items.*.transactionItemId').notEmpty().withMessage('Transaction item ID is required'),
  body('items.*.quantity').isInt({ min: 1 }).withMessage('Quantity must be at least 1'),
  body('items.*.reason').optional(),
  body('items.*.condition').optional().isIn(['good', 'damaged', 'defective']),
  body('refundMethod').optional().isIn(['cash', 'card', 'store_credit', 'original_payment']),
  body('notes').optional()
];

const validateApproveReturn = [
  param('id').isInt().withMessage('Invalid return ID'),
  body('notes').optional(),
  body('restockItems').optional().isBoolean()
];

const validateRejectReturn = [
  param('id').isInt().withMessage('Invalid return ID'),
  body('rejectionReason').notEmpty().withMessage('Rejection reason is required')
];

const validateCompleteReturn = [
  param('id').isInt().withMessage('Invalid return ID'),
  body('refundMethod').optional().isIn(['cash', 'card', 'store_credit', 'original_payment']),
  body('refundAmount').optional().isFloat({ min: 0 }),
  body('paymentReference').optional()
];

const validateCancelReturn = [
  param('id').isInt().withMessage('Invalid return ID'),
  body('reason').optional()
];

const validateUpdateReturn = [
  param('id').isInt().withMessage('Invalid return ID'),
  body('reason').optional(),
  body('notes').optional(),
  body('refundMethod').optional().isIn(['cash', 'card', 'store_credit', 'original_payment']),
  body('restockingFee').optional().isFloat({ min: 0 })
];

const validateBatchApprove = [
  body('returnIds').isArray({ min: 1 }).withMessage('Return IDs array is required'),
  body('returnIds.*').isInt().withMessage('Invalid return ID'),
  body('restockItems').optional().isBoolean()
];

const validateAutoApprove = [
  body('maxAmount').optional().isFloat({ min: 0 }),
  body('maxDaysFromPurchase').optional().isInt({ min: 0 })
];

// Routes

/**
 * @route   POST /api/returns
 * @desc    Create a new return
 * @access  Private
 */
router.post('/', authenticate, returnController.createReturn);

/**
 * @route   GET /api/returns
 * @desc    Get all returns with filters
 * @access  Private
 */
router.get('/', authenticate, returnController.getReturns);

/**
 * @route   GET /api/returns/stats
 * @desc    Get return statistics
 * @access  Private
 */
router.get('/stats', authenticate, returnController.getReturnStatistics);

/**
 * @route   GET /api/returns/export/csv
 * @desc    Export returns to CSV
 * @access  Private
 */
router.get('/export/csv', authenticate, returnController.exportReturnsToCSV);

/**
 * @route   GET /api/returns/reports/date-range
 * @desc    Get returns by date range with aggregations
 * @access  Private
 */
router.get('/reports/date-range', authenticate, returnController.getReturnsByDateRange);

/**
 * @route   GET /api/returns/reports/top-products
 * @desc    Get top returned products
 * @access  Private
 */
router.get('/reports/top-products', authenticate, returnController.getTopReturnedProducts);

/**
 * @route   GET /api/returns/reports/return-rate
 * @desc    Get return rate analysis
 * @access  Private
 */
router.get('/reports/return-rate', authenticate, returnController.getReturnRateAnalysis);

/**
 * @route   GET /api/returns/reports/refund-summary
 * @desc    Get refund summary
 * @access  Private
 */
router.get('/reports/refund-summary', authenticate, returnController.getRefundSummary);

/**
 * @route   POST /api/returns/batch/approve
 * @desc    Batch approve returns
 * @access  Private
 */
router.post('/batch/approve', authenticate, validateBatchApprove, returnController.batchApproveReturns);

/**
 * @route   POST /api/returns/auto-approve
 * @desc    Process automatic approval for eligible returns
 * @access  Private
 */
router.post('/auto-approve', authenticate, validateAutoApprove, returnController.autoApproveEligibleReturns);

/**
 * @route   GET /api/returns/check/:transactionId/:transactionItemId
 * @desc    Check if item can be returned
 * @access  Private
 */
router.get('/check/:transactionId/:transactionItemId', authenticate, returnController.checkReturnEligibility);

/**
 * @route   GET /api/returns/customer/:customerId
 * @desc    Get returns for a specific customer
 * @access  Private
 */
router.get('/customer/:customerId', authenticate, returnController.getCustomerReturns);

/**
 * @route   GET /api/returns/:id
 * @desc    Get single return by ID
 * @access  Private
 */
router.get('/:id', authenticate, returnController.getReturnById);

/**
 * @route   GET /api/returns/:id/receipt
 * @desc    Generate return receipt
 * @access  Private
 */
router.get('/:id/receipt', authenticate, returnController.generateReturnReceipt);

/**
 * @route   GET /api/returns/:id/timeline
 * @desc    Get return timeline/history
 * @access  Private
 */
router.get('/:id/timeline', authenticate, returnController.getReturnTimeline);

/**
 * @route   PUT /api/returns/:id
 * @desc    Update return
 * @access  Private
 */
router.put('/:id', authenticate, validateUpdateReturn, returnController.updateReturn);

/**
 * @route   PUT /api/returns/:id/approve
 * @desc    Approve return
 * @access  Private
 */
router.put('/:id/approve', authenticate, validateApproveReturn, returnController.approveReturn);

/**
 * @route   PUT /api/returns/:id/reject
 * @desc    Reject return
 * @access  Private
 */
router.put('/:id/reject', authenticate, validateRejectReturn, returnController.rejectReturn);

/**
 * @route   PUT /api/returns/:id/complete
 * @desc    Complete return with refund
 * @access  Private
 */
router.put('/:id/complete', authenticate, validateCompleteReturn, returnController.completeReturn);

/**
 * @route   PUT /api/returns/:id/cancel
 * @desc    Cancel return
 * @access  Private
 */
router.put('/:id/cancel', authenticate, validateCancelReturn, returnController.cancelReturn);

/**
 * @route   DELETE /api/returns/:id
 * @desc    Delete return (soft delete)
 * @access  Private
 */
router.delete('/:id', authenticate, returnController.deleteReturn);

module.exports = router;