const express = require('express');
const router = express.Router();
const orderController = require('../controllers/orderController');

// Import YOUR existing auth middleware
const { 
  authenticate, 
  authorize
} = require('../middleware/auth');

// Import validators (optional - can be commented out)
const { 
  validateOrder, 
  validateOrderUpdate, 
  validateBulkUpdate,
  validateCancelOrder,
  validateOrderItemsUpdate,
  validateOrderQuery,
  validateOrderId,
  validateOrderNumber,
  validateUserId,
  validateReorder,
  validateExportQuery,
  validateStatsQuery
} = require('../middleware/orderValidator');

// Import rate limiters (optional - can be commented out)
// const { 
//   rateLimiter,
//   createOrderLimiter,
//   searchLimiter,
//   exportLimiter
// } = require('../middleware/rateLimiter');

// =============================================================================
// PUBLIC ROUTES (No Authentication Required)
// =============================================================================

/**
 * @route   GET /api/orders/track/:orderNumber
 * @desc    Track order by order number (public access for customers)
 * @access  Public
 */
router.get('/track/:orderNumber', 
  validateOrderNumber,
  orderController.trackOrder
);

// =============================================================================
// CUSTOMER ROUTES (Authentication Required)
// =============================================================================

/**
 * @route   POST /api/orders
 * @desc    Create a new order
 * @access  Private (Customer/Cashier)
 */
router.post(
  '/',
  authenticate,
  // createOrderLimiter, // Uncomment if using rate limiter
  validateOrder,
  orderController.createOrder
);

/**
 * @route   GET /api/orders/customer/:userId
 * @desc    Get all orders for a specific customer
 * @access  Private (Customer - own orders, Admin/Manager - all)
 */
router.get(
  '/customer/:userId',
  authenticate,
  validateUserId,
  orderController.getCustomerOrders
);

/**
 * @route   GET /api/orders/:orderId
 * @desc    Get single order details
 * @access  Private (Customer - own order, Admin/Manager - all)
 */
router.get(
  '/:orderId',
  authenticate,
  validateOrderId,
  orderController.getOrderById
);

/**
 * @route   POST /api/orders/:orderId/cancel
 * @desc    Cancel an order
 * @access  Private (Customer - own order, Admin/Manager - all)
 */
router.post(
  '/:orderId/cancel',
  authenticate,
  validateCancelOrder,
  orderController.cancelOrder
);

/**
 * @route   POST /api/orders/:orderId/reorder
 * @desc    Reorder from an existing order
 * @access  Private (Customer)
 */
router.post(
  '/:orderId/reorder',
  authenticate,
  // rateLimiter(5, 15 * 60), // 5 requests per 15 minutes
  validateReorder,
  orderController.reorder
);

/**
 * @route   GET /api/orders/:orderId/invoice
 * @desc    Get order invoice
 * @access  Private (Customer - own order, Admin/Manager - all)
 */
router.get(
  '/:orderId/invoice',
  authenticate,
  validateOrderId,
  orderController.getOrderInvoice
);

// =============================================================================
// ADMIN/MANAGER ROUTES (Admin/Manager Access)
// =============================================================================

/**
 * @route   GET /api/orders
 * @desc    Get all orders with filtering, pagination, and sorting
 * @access  Private (Admin/Manager)
 */
router.get(
  '/',
//   authenticate,
//   authorize('admin', 'manager', 'super_admin'),
  validateOrderQuery,
  orderController.getAllOrders
);

/**
 * @route   GET /api/orders/stats/overview
 * @desc    Get comprehensive order statistics
 * @access  Private (Admin/Manager)
 */
router.get(
  '/stats/overview',
//   authenticate,
//   authorize('admin', 'manager', 'super_admin'),
//   validateStatsQuery,
  orderController.getOrderStats
);

/**
 * @route   GET /api/orders/stats/count-by-status
 * @desc    Get order count grouped by status
 * @access  Private (Admin/Manager)
 */
router.get(
  '/stats/count-by-status',
//   authenticate,
//   authorize('admin', 'manager', 'super_admin'),
  orderController.getOrderCountByStatus
);

/**
 * @route   GET /api/orders/recent/list
 * @desc    Get recent orders
 * @access  Private (Admin/Manager)
 */
router.get(
  '/recent/list',
  authenticate,
//   authorize('admin', 'manager', 'super_admin', 'cashier'),
  orderController.getRecentOrders
);

/**
 * @route   GET /api/orders/pending/list
 * @desc    Get pending orders
 * @access  Private (Admin/Manager/Cashier)
 */
router.get(
  '/pending/list',
  authenticate,
//   authorize('admin', 'manager', 'super_admin', 'cashier'),
  orderController.getPendingOrders
);

/**
 * @route   GET /api/orders/search
 * @desc    Search orders
 * @access  Private (Admin/Manager)
 */
router.get(
  '/search',
  authenticate,
  authorize('admin', 'manager', 'super_admin', 'cashier'),
  // searchLimiter, // Uncomment if using rate limiter
  orderController.searchOrders
);

/**
 * @route   PUT /api/orders/:orderId/status
 * @desc    Update order status
 * @access  Private (Admin/Manager/Warehouse Staff)
 */
router.put(
  '/:orderId/status',
  authenticate,
  authorize('admin', 'manager', 'super_admin', 'warehouse', 'cashier'),
  validateOrderUpdate,
  orderController.updateOrderStatus
);

/**
 * @route   PUT /api/orders/:orderId/payment-status
 * @desc    Update payment status
 * @access  Private (Admin/Manager/Finance)
 */
router.put(
  '/:orderId/payment-status',
  authenticate,
  authorize('admin', 'manager', 'super_admin', 'finance', 'cashier'),
  orderController.updatePaymentStatus
);

/**
 * @route   PUT /api/orders/:orderId/items
 * @desc    Update order items
 * @access  Private (Admin/Manager)
 */
router.put(
  '/:orderId/items',
  authenticate,
  authorize('admin', 'manager', 'super_admin'),
  validateOrderItemsUpdate,
  orderController.updateOrderItems
);

/**
 * @route   POST /api/orders/bulk-update
 * @desc    Bulk update multiple orders
 * @access  Private (Admin/Manager)
 */
router.post(
  '/bulk-update',
  authenticate,
  authorize('admin', 'manager', 'super_admin'),
  validateBulkUpdate,
  orderController.bulkUpdateOrders
);

/**
 * @route   GET /api/orders/export/csv
 * @desc    Export orders to CSV
 * @access  Private (Admin/Manager)
 */
router.get(
  '/export/csv',
  authenticate,
  authorize('admin', 'manager', 'super_admin'),
  // exportLimiter, // Uncomment if using rate limiter
  validateExportQuery,
  orderController.exportOrders
);

/**
 * @route   DELETE /api/orders/:orderId
 * @desc    Delete an order (soft delete)
 * @access  Private (Admin only)
 */
router.delete(
  '/:orderId',
  authenticate,
  authorize('admin', 'super_admin'),
  validateOrderId,
  orderController.deleteOrder
);

// =============================================================================
// ERROR HANDLING FOR UNDEFINED ROUTES
// =============================================================================
router.use((req, res) => {
  res.status(404).json({
    success: false,
    message: 'Order route not found'
  });
});

module.exports = router;