/**
 * Inventory Management Routes
 * Route definitions for inventory management endpoints
 */

// Import Express Router
const express = require('express');
// Create router instance
const router = express.Router();
// Import inventory controllers
const inventoryControllers = require('../controllers');
const rmInventoryController = require('../controllers/rmInventoryController');
// Import inventory validations
const inventoryValidations = require('../validations');
const rmInventoryValidations = require('../validations/rmInventoryValidations');
const {
  validateGetQuantity,
  validateCheckAvailability,
  validateGetInventory,
  validateListInventory,
  validateAdjustInventory,
  validateSetInventoryQuantity,
  validateSetReorderLevel,
  validateGetInventoryMovements,
} = inventoryValidations;
// Import authentication middleware
const { authenticate, requireRole } = require('../../../middlewares/auth');

/**
 * @swagger
 * components:
 *   schemas:
 *     Inventory:
 *       type: object
 *       properties:
 *         id:
 *           type: integer
 *         product_id:
 *           type: integer
 *         quantity:
 *           type: number
 *         reorder_level:
 *           type: number
 *         product:
 *           $ref: '#/components/schemas/Product'
 */

/**
 * @swagger
 * /inventory/quantity:
 *   get:
 *     summary: Get inventory quantity
 *     description: Get current inventory quantity for a product
 *     tags: [Inventory]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: product_id
 *         required: true
 *         schema:
 *           type: integer
 *         description: Product ID
 *     responses:
 *       200:
 *         description: Quantity retrieved successfully
 *       400:
 *         description: Validation error
 *       401:
 *         description: Unauthorized
 *       404:
 *         description: Product not found
 */
router.get('/quantity', authenticate, validateGetQuantity, inventoryControllers.getQuantity);

/**
 * @swagger
 * /inventory/check-availability:
 *   get:
 *     summary: Check stock availability
 *     description: Check if product is available in required quantity
 *     tags: [Inventory]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: product_id
 *         required: true
 *         schema:
 *           type: integer
 *         description: Product ID
 *       - in: query
 *         required: false
 *         schema:
 *           type: integer
 *         description: Variant ID (optional)
 *       - in: query
 *         name: quantity
 *         required: true
 *         schema:
 *           type: number
 *         description: Required quantity
 *     responses:
 *       200:
 *         description: Availability checked successfully
 *       400:
 *         description: Validation error
 *       401:
 *         description: Unauthorized
 *       404:
 *         description: Product not found
 */
router.get('/check-availability', authenticate, validateCheckAvailability, inventoryControllers.checkAvailability);

/**
 * @swagger
 * /inventory:
 *   get:
 *     summary: List inventory
 *     description: List inventory records with filters and pagination. Use low_stock=true to get items below reorder level.
 *     tags: [Inventory]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *         description: Page number
 *       - in: query
 *         name: limit
 *         schema:
 *           type: integer
 *         description: Items per page
 *       - in: query
 *         name: product_id
 *         schema:
 *           type: integer
 *         description: Filter by product ID
 *       - in: query
 *         name: low_stock
 *         schema:
 *           type: boolean
 *         description: Filter by low stock status (returns items where quantity <= reorder_level)
 *     responses:
 *       200:
 *         description: Inventory list retrieved successfully
 *       400:
 *         description: Validation error
 *       401:
 *         description: Unauthorized
 */
router.get('/', authenticate, validateListInventory, inventoryControllers.listInventory);

// ============================================
// UID-Based Inventory Items Routes (MUST come before /:productId route)
// ============================================

/**
 * @swagger
 * /api/inventory/items:
 *   post:
 *     summary: Create inventory item with UID
 *     tags: [Inventory]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - product_id
 *               - source
 *             properties:
 *               product_id:
 *                 type: integer
 *                 description: Product ID
 *               source:
 *                 type: string
 *                 enum: [GRN, PRODUCTION, RETURN]
 *                 description: Source of inventory item
 *               uid:
 *                 type: string
 *                 description: UID (optional, will be generated if not provided)
 *               barcode:
 *                 type: string
 *                 description: Barcode (optional, will be generated if not provided)
 *     responses:
 *       201:
 *         description: Inventory item created successfully
 *       400:
 *         description: Validation error
 *       404:
 *         description: Product not found
 */
router.post(
  '/items', // POST /api/inventory/items
  authenticate, // Require authentication
  requireRole(['manager', 'system_admin']), // Require role
  inventoryValidations.validateCreateInventoryItem, // Validate request
  inventoryControllers.createInventoryItem // Create inventory item controller
);

/**
 * @swagger
 * /api/inventory/items:
 *   get:
 *     summary: List inventory items with filters
 *     tags: [Inventory]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *           default: 1
 *         description: Page number
 *       - in: query
 *         name: limit
 *         schema:
 *           type: integer
 *           default: 10
 *         description: Items per page
 *       - in: query
 *         name: product_id
 *         schema:
 *           type: integer
 *         description: Filter by product ID
 *       - in: query
 *         name: status
 *         schema:
 *           type: string
 *           enum: [IN_STOCK, RESERVED, SOLD, RETURNED, DAMAGED, SCRAPPED]
 *         description: Filter by status
 *       - in: query
 *         name: source
 *         schema:
 *           type: string
 *           enum: [GRN, PRODUCTION, RETURN]
 *         description: Filter by source
 *     responses:
 *       200:
 *         description: Inventory items retrieved successfully
 */
router.get(
  '/items', // GET /api/inventory/items
  authenticate, // Require authentication
  inventoryValidations.validateListInventoryItems, // Validate request
  inventoryControllers.listInventoryItems // List inventory items controller
);

/**
 * @swagger
 * /api/inventory/items/{uid}/scan:
 *   get:
 *     summary: Scan inventory item by UID/barcode
 *     tags: [Inventory]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: uid
 *         required: true
 *         schema:
 *           type: string
 *         description: UID or barcode
 *     responses:
 *       200:
 *         description: Inventory item scanned successfully (includes QR code)
 *       404:
 *         description: Inventory item not found
 */
router.get(
  '/items/:uid/scan', // GET /api/inventory/items/:uid/scan
  authenticate, // Require authentication
  inventoryValidations.validateScanInventoryItem, // Validate request
  inventoryControllers.scanInventoryItem // Scan inventory item controller
);

/**
 * @swagger
 * /api/inventory/items/{uid}/status:
 *   put:
 *     summary: Update inventory item status
 *     tags: [Inventory]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: uid
 *         required: true
 *         schema:
 *           type: string
 *         description: UID or barcode
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - status
 *             properties:
 *               status:
 *                 type: string
 *                 enum: [IN_STOCK, RESERVED, SOLD, RETURNED, DAMAGED, SCRAPPED]
 *                 description: New status
 *               reason:
 *                 type: string
 *                 description: Reason for status change (optional)
 *     responses:
 *       200:
 *         description: Inventory item status updated successfully
 *       400:
 *         description: Validation error
 *       404:
 *         description: Inventory item not found
 */
router.put(
  '/items/:uid/status', // PUT /api/inventory/items/:uid/status
  authenticate, // Require authentication
  requireRole(['manager', 'system_admin']), // Require role
  inventoryValidations.validateUpdateInventoryItemStatus, // Validate request
  inventoryControllers.updateInventoryItemStatus // Update inventory item status controller
);

/**
 * @swagger
 * /api/inventory/items/{uid}:
 *   get:
 *     summary: Get inventory item by UID/barcode
 *     tags: [Inventory]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: uid
 *         required: true
 *         schema:
 *           type: string
 *         description: UID or barcode
 *     responses:
 *       200:
 *         description: Inventory item retrieved successfully
 *       404:
 *         description: Inventory item not found
 */
router.get(
  '/items/:uid', // GET /api/inventory/items/:uid (MUST come after /items/:uid/scan)
  authenticate, // Require authentication
  inventoryValidations.validateGetInventoryItemByUID, // Validate request
  inventoryControllers.getInventoryItemByUID // Get inventory item controller
);

/**
 * @swagger
 * /inventory/{productId}:
 *   get:
 *     summary: Get inventory record
 *     description: Get inventory record with product details
 *     tags: [Inventory]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: productId
 *         required: true
 *         schema:
 *           type: integer
 *         description: Product ID
 *     responses:
 *       200:
 *         description: Inventory retrieved successfully
 *       400:
 *         description: Validation error
 *       401:
 *         description: Unauthorized
 *       404:
 *         description: Product not found
 */
router.get('/:productId', authenticate, validateGetInventory, inventoryControllers.getInventory);

/**
 * @swagger
 * /inventory/{productId}/movements:
 *   get:
 *     summary: Get inventory movements
 *     description: Get inventory movement history for a product
 *     tags: [Inventory]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: productId
 *         required: true
 *         schema:
 *           type: integer
 *         description: Product ID
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *         description: Page number
 *       - in: query
 *         name: limit
 *         schema:
 *           type: integer
 *         description: Items per page
 *     responses:
 *       200:
 *         description: Movements retrieved successfully
 *       400:
 *         description: Validation error
 *       401:
 *         description: Unauthorized
 *       404:
 *         description: Product not found
 */
router.get('/:productId/movements', authenticate, validateGetInventoryMovements, inventoryControllers.getInventoryMovements);

/**
 * @swagger
 * /inventory/adjust:
 *   post:
 *     summary: Adjust inventory quantity
 *     description: Adjust inventory quantity (increase/decrease) - Manager/Admin only
 *     tags: [Inventory]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - product_id
 *               - quantity_change
 *               - reason
 *             properties:
 *               product_id:
 *                 type: integer
 *               quantity_change:
 *                 type: number
 *                 description: Positive for increase, negative for decrease
 *               reason:
 *                 type: string
 *                 enum: [GRN, SALE, SALE_RETURN, PRODUCTION_CONSUME, PRODUCTION_OUTPUT, ADJUSTMENT]
 *               reference_id:
 *                 type: integer
 *     responses:
 *       200:
 *         description: Inventory adjusted successfully
 *       400:
 *         description: Validation error or insufficient stock
 *       401:
 *         description: Unauthorized
 *       403:
 *         description: Forbidden (insufficient permissions)
 *       404:
 *         description: Product not found
 */
router.post('/adjust', authenticate, requireRole(['manager', 'system_admin']), validateAdjustInventory, inventoryControllers.adjustInventory);

/**
 * @swagger
 * /inventory/set-quantity:
 *   put:
 *     summary: Set inventory quantity
 *     description: Set inventory to a specific quantity (absolute value) - Manager/Admin only
 *     tags: [Inventory]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - product_id
 *               - quantity
 *             properties:
 *               product_id:
 *                 type: integer
 *               quantity:
 *                 type: number
 *                 minimum: 0
 *               notes:
 *                 type: string
 *     responses:
 *       200:
 *         description: Inventory quantity set successfully
 *       400:
 *         description: Validation error
 *       401:
 *         description: Unauthorized
 *       403:
 *         description: Forbidden (insufficient permissions)
 *       404:
 *         description: Product not found
 */
router.put('/set-quantity', authenticate, requireRole(['manager', 'system_admin']), validateSetInventoryQuantity, inventoryControllers.setInventoryQuantity);

/**
 * @swagger
 * /inventory/reorder-level:
 *   put:
 *     summary: Set reorder level
 *     description: Set reorder level for a product/variant - Manager/Admin only
 *     tags: [Inventory]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - product_id
 *               - reorder_level
 *             properties:
 *               product_id:
 *                 type: integer
 *               reorder_level:
 *                 type: number
 *                 minimum: 0
 *     responses:
 *       200:
 *         description: Reorder level set successfully
 *       400:
 *         description: Validation error
 *       401:
 *         description: Unauthorized
 *       403:
 *         description: Forbidden (insufficient permissions)
 *       404:
 *         description: Product not found
 */
router.put('/reorder-level', authenticate, requireRole(['manager', 'system_admin']), validateSetReorderLevel, inventoryControllers.setReorderLevel);


// ============================================
// RM Inventory Routes (Dimension-Based)
// ============================================

/**
 * @swagger
 * /api/inventory/rm/{productId}/pieces:
 *   get:
 *     summary: List RM inventory pieces with dimensions
 *     description: List all RM inventory pieces for a product with dimension details and filtering
 *     tags: [Inventory]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: productId
 *         required: true
 *         schema:
 *           type: integer
 *         description: RM Product ID
 *       - in: query
 *         name: status
 *         schema:
 *           type: string
 *           enum: [FULL, USABLE, WASTE, SCRAP]
 *         description: Filter by piece status
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *           default: 1
 *         description: Page number
 *       - in: query
 *         name: limit
 *         schema:
 *           type: integer
 *           default: 50
 *         description: Items per page
 *       - in: query
 *         name: min_length
 *         schema:
 *           type: number
 *         description: Minimum length filter
 *       - in: query
 *         name: max_length
 *         schema:
 *           type: number
 *         description: Maximum length filter
 *       - in: query
 *         name: min_width
 *         schema:
 *           type: number
 *         description: Minimum width filter
 *       - in: query
 *         name: max_width
 *         schema:
 *           type: number
 *         description: Maximum width filter
 *       - in: query
 *         name: unit
 *         schema:
 *           type: string
 *           enum: [inch, cm, m]
 *         description: Unit filter
 *     responses:
 *       200:
 *         description: RM inventory pieces retrieved successfully
 *       400:
 *         description: Validation error
 *       401:
 *         description: Unauthorized
 *       404:
 *         description: Product not found
 */
router.get(
  '/rm/:productId/pieces',
  authenticate,
  rmInventoryValidations.validateListRMInventoryPieces,
  rmInventoryController.listRMInventoryPieces
);

/**
 * @swagger
 * /api/inventory/rm/{productId}/summary:
 *   get:
 *     summary: Get RM inventory summary with aggregated dimensions
 *     description: Get aggregated dimension summary for RM product including area calculations and utilization metrics
 *     tags: [Inventory]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: productId
 *         required: true
 *         schema:
 *           type: integer
 *         description: RM Product ID
 *       - in: query
 *         name: unit
 *         schema:
 *           type: string
 *           enum: [inch, cm, m]
 *         description: Unit for summary calculations (defaults to product unit)
 *     responses:
 *       200:
 *         description: RM inventory summary retrieved successfully
 *       400:
 *         description: Validation error
 *       401:
 *         description: Unauthorized
 *       404:
 *         description: Product not found
 */
router.get(
  '/rm/:productId/summary',
  authenticate,
  rmInventoryValidations.validateGetRMInventorySummary,
  rmInventoryController.getRMInventorySummary
);

/**
 * @swagger
 * /api/inventory/rm/{productId}/write-off:
 *   post:
 *     summary: Write off scrap dimensions
 *     description: Write off SCRAP or WASTE pieces that are no longer usable
 *     tags: [Inventory]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: productId
 *         required: true
 *         schema:
 *           type: integer
 *         description: RM Product ID
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - piece_ids
 *               - reason
 *             properties:
 *               piece_ids:
 *                 type: array
 *                 items:
 *                   type: integer
 *                 description: Array of piece IDs to write off
 *               reason:
 *                 type: string
 *                 description: Reason for write-off
 *               notes:
 *                 type: string
 *                 description: Additional notes (optional)
 *     responses:
 *       200:
 *         description: Pieces written off successfully
 *       400:
 *         description: Validation error
 *       401:
 *         description: Unauthorized
 *       403:
 *         description: Forbidden (insufficient permissions)
 *       404:
 *         description: Product not found
 */
router.post(
  '/rm/:productId/write-off',
  authenticate,
  requireRole(['manager', 'system_admin']),
  rmInventoryValidations.validateWriteOffScrapDimensions,
  rmInventoryController.writeOffScrapDimensions
);

// ============================================
// Inventory Reconciliation Routes
// ============================================

/**
 * @swagger
 * /api/inventory/reconciliation/report:
 *   get:
 *     summary: Get inventory reconciliation report
 *     tags: [Inventory]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: product_id
 *         schema:
 *           type: integer
 *         description: Optional product ID to check specific product
 *     responses:
 *       200:
 *         description: Reconciliation report retrieved successfully
 */
router.get(
  '/reconciliation/report', // GET /api/inventory/reconciliation/report
  authenticate, // Require authentication
  requireRole(['manager', 'system_admin']), // Require manager/admin role
  inventoryControllers.getReconciliationReport // Get reconciliation report controller
);

/**
 * @swagger
 * /api/inventory/reconciliation/check:
 *   get:
 *     summary: Check for inventory discrepancies
 *     tags: [Inventory]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: product_id
 *         schema:
 *           type: integer
 *         description: Optional product ID to check specific product
 *     responses:
 *       200:
 *         description: Discrepancy check completed
 */
router.get(
  '/reconciliation/check', // GET /api/inventory/reconciliation/check
  authenticate, // Require authentication
  requireRole(['manager', 'system_admin']), // Require manager/admin role
  inventoryControllers.checkDiscrepancies // Check discrepancies controller
);

/**
 * @swagger
 * /api/inventory/reconciliation/auto-reconcile:
 *   post:
 *     summary: Auto-reconcile inventory discrepancies
 *     tags: [Inventory]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               product_id:
 *                 type: integer
 *                 description: Optional product ID to reconcile specific product
 *     responses:
 *       200:
 *         description: Reconciliation completed successfully
 */
router.post(
  '/reconciliation/auto-reconcile', // POST /api/inventory/reconciliation/auto-reconcile
  authenticate, // Require authentication
  requireRole(['manager', 'system_admin']), // Require manager/admin role
  inventoryControllers.autoReconcile // Auto-reconcile controller
);

// Export router
module.exports = router;
