/**
 * Production Routes
 * API routes for production operations
 */

// Import Express router
const express = require('express');
// Create router instance
const router = express.Router();
// Import production controllers
const productionControllers = require('../controllers');
// Import validation rules
const productionValidations = require('../validations');
// Import authentication middleware
const { authenticate, requireRole } = require('../../../middlewares/auth');

// ============================================
// BOM Routes
// ============================================

/**
 * @swagger
 * /api/production/boms:
 *   post:
 *     summary: Create BOM
 *     tags: [Production]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - fg_product_id
 *               - items
 *             properties:
 *               fg_product_id:
 *                 type: integer
 *                 description: Finished good product ID
 *               items:
 *                 type: array
 *                 description: BOM items (raw materials)
 *                 items:
 *                   type: object
 *                   required:
 *                     - rm_product_id
 *                     - quantity_per_unit
 *                   properties:
 *                     rm_product_id:
 *                       type: integer
 *                       description: Raw material product ID
 *                     quantity_per_unit:
 *                       type: number
 *                       description: Quantity of raw material needed per unit of finished good
 */
router.post(
  '/boms', // POST /api/production/boms
  authenticate, // Require authentication
  requireRole(['manager', 'system_admin']), // Require role
  productionValidations.validateCreateBOM, // Validate request
  productionControllers.createBOM // Create BOM controller
);

/**
 * @swagger
 * /api/production/boms:
 *   get:
 *     summary: List BOMs
 *     tags: [Production]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: fg_product_id
 *         schema:
 *           type: integer
 *         description: Filter by finished good product ID
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *         description: Page number
 *       - in: query
 *         name: limit
 *         schema:
 *           type: integer
 *         description: Items per page
 */
router.get(
  '/boms', // GET /api/production/boms
  authenticate, // Require authentication
  productionValidations.validateListBOMs, // Validate request
  productionControllers.listBOMs // List BOMs controller
);

/**
 * @swagger
 * /api/production/boms/{id}:
 *   get:
 *     summary: Get BOM by ID
 *     tags: [Production]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: BOM ID
 */
router.get(
  '/boms/:id', // GET /api/production/boms/:id
  authenticate, // Require authentication
  productionValidations.validateGetBOM, // Validate request
  productionControllers.getBOM // Get BOM controller
);

/**
 * @swagger
 * /api/production/boms/variant/{productId}:
 *   get:
 *     summary: Get BOM by product ID (DEPRECATED - use /boms/product/{productId} instead)
 *     tags: [Production]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: productId
 *         required: true
 *         schema:
 *           type: integer
 *         description: Finished good variant ID
 */
router.get(
  '/boms/variant/:productId', // GET /api/production/boms/variant/:productId
  authenticate, // Require authentication
  productionValidations.validateGetBOMByProduct, // Validate request
  productionControllers.getBOMByProduct // Get BOM by variant controller
);

/**
 * @swagger
 * /api/production/boms/{id}:
 *   put:
 *     summary: Update BOM
 *     tags: [Production]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: BOM ID
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               items:
 *                 type: array
 *                 description: BOM items to replace existing items
 *                 items:
 *                   type: object
 *                   required:
 *                     - rm_product_id
 *                     - quantity_per_unit
 *                   properties:
 *                     rm_product_id:
 *                       type: integer
 *                       description: Raw material product ID
 *                     quantity_per_unit:
 *                       type: number
 *                       description: Quantity of raw material needed per unit of finished good
 */
router.put(
  '/boms/:id', // PUT /api/production/boms/:id
  authenticate, // Require authentication
  requireRole(['manager', 'system_admin']), // Require role
  productionValidations.validateUpdateBOM, // Validate request
  productionControllers.updateBOM // Update BOM controller
);

/**
 * @swagger
 * /api/production/boms/{id}:
 *   delete:
 *     summary: Delete BOM
 *     tags: [Production]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: BOM ID
 */
router.delete(
  '/boms/:id', // DELETE /api/production/boms/:id
  authenticate, // Require authentication
  requireRole(['manager', 'system_admin']), // Require role
  productionValidations.validateDeleteBOM, // Validate request
  productionControllers.deleteBOM // Delete BOM controller
);

// ============================================
// Production Order Routes
// ============================================

/**
 * @swagger
 * /api/production/orders:
 *   post:
 *     summary: Create production order
 *     tags: [Production]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - fg_product_id
 *               - quantity
 *             properties:
 *               fg_product_id:
 *                 type: integer
 *                 description: Finished good product ID
 *               quantity:
 *                 type: number
 *                 description: Quantity to produce
 *               status:
 *                 type: string
 *                 enum: [DRAFT, CONFIRMED]
 *                 description: Production order status
 */
router.post(
  '/orders', // POST /api/production/orders
  authenticate, // Require authentication
  requireRole(['manager', 'system_admin', 'cashier']), // Require role
  productionValidations.validateCreateProductionOrder, // Validate request
  productionControllers.createProductionOrder // Create production order controller
);

/**
 * @swagger
 * /api/production/orders:
 *   get:
 *     summary: List production orders
 *     tags: [Production]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: fg_product_id
 *         schema:
 *           type: integer
 *         description: Filter by finished good product ID
 *       - in: query
 *         name: status
 *         schema:
 *           type: string
 *           enum: [DRAFT, CONFIRMED]
 *         description: Filter by status
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *         description: Page number
 *       - in: query
 *         name: limit
 *         schema:
 *           type: integer
 *         description: Items per page
 */
router.get(
  '/orders', // GET /api/production/orders
  authenticate, // Require authentication
  productionValidations.validateListProductionOrders, // Validate request
  productionControllers.listProductionOrders // List production orders controller
);

/**
 * @swagger
 * /api/production/orders/{id}:
 *   get:
 *     summary: Get production order by ID
 *     tags: [Production]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: Production order ID
 */
router.get(
  '/orders/:id', // GET /api/production/orders/:id
  authenticate, // Require authentication
  productionValidations.validateGetProductionOrder, // Validate request
  productionControllers.getProductionOrder // Get production order controller
);

/**
 * @swagger
 * /api/production/orders/{id}/check-availability:
 *   get:
 *     summary: Check raw material availability for production order
 *     tags: [Production]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: Production order ID
 */
router.get(
  '/orders/:id/check-availability', // GET /api/production/orders/:id/check-availability
  authenticate, // Require authentication
  productionValidations.validateCheckAvailability, // Validate request
  productionControllers.checkAvailability // Check availability controller
);

/**
 * @swagger
 * /api/production/orders/{id}/optimization-suggestions:
 *   get:
 *     summary: Get production quantity optimization suggestions
 *     description: Analyzes available materials and suggests optimal production quantities with waste analysis
 *     tags: [Production]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: Production order ID
 *       - in: query
 *         name: maxSuggestions
 *         schema:
 *           type: integer
 *           default: 5
 *         description: Maximum number of suggestions to return
 *       - in: query
 *         name: includeWasteAnalysis
 *         schema:
 *           type: boolean
 *           default: true
 *         description: Include waste analysis in suggestions
 *     responses:
 *       200:
 *         description: Optimization suggestions retrieved successfully
 *       400:
 *         description: Validation error
 *       401:
 *         description: Unauthorized
 *       404:
 *         description: Production order not found
 */
router.get(
  '/orders/:id/optimization-suggestions',
  authenticate,
  productionValidations.validateGetProductionOrder, // Reuse existing validation
  productionControllers.getProductionOptimizationSuggestions
);

/**
 * @swagger
 * /api/production/orders/{id}/cutting-operations:
 *   get:
 *     summary: Get cutting operations for production order
 *     description: Retrieves all cutting operations performed for a production order with waste details
 *     tags: [Production]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: Production order ID
 *     responses:
 *       200:
 *         description: Cutting operations retrieved successfully
 *       400:
 *         description: Validation error
 *       401:
 *         description: Unauthorized
 *       404:
 *         description: Production order not found
 */
router.get(
  '/orders/:id/cutting-operations',
  authenticate,
  productionValidations.validateGetProductionOrder, // Reuse existing validation
  productionControllers.getCuttingOperations
);

/**
 * @swagger
 * /api/production/orders/{id}/waste-suggestions:
 *   get:
 *     summary: Get waste piece suggestions for production planning
 *     description: Suggests available waste pieces that match BOM requirements for cost savings
 *     tags: [Production]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: Production order ID
 *     responses:
 *       200:
 *         description: Waste suggestions retrieved successfully
 *       400:
 *         description: Validation error
 *       401:
 *         description: Unauthorized
 *       404:
 *         description: Production order not found
 */
router.get(
  '/orders/:id/waste-suggestions',
  authenticate,
  productionValidations.validateGetProductionOrder, // Reuse existing validation
  productionControllers.getWastePieceSuggestions
);

/**
 * @swagger
 * /api/production/orders/{id}/material-traceability:
 *   get:
 *     summary: Get material traceability for production order
 *     description: Provides complete traceability from source pieces to final products
 *     tags: [Production]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: Production order ID
 *     responses:
 *       200:
 *         description: Material traceability retrieved successfully
 *       400:
 *         description: Validation error
 *       401:
 *         description: Unauthorized
 *       404:
 *         description: Production order not found
 */
router.get(
  '/orders/:id/material-traceability',
  authenticate,
  productionValidations.validateGetProductionOrder, // Reuse existing validation
  productionControllers.getMaterialTraceability
);

/**
 * @swagger
 * /api/production/orders/{id}/confirm:
 *   post:
 *     summary: Confirm production (consume RM and create FG)
 *     tags: [Production]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: Production order ID
 *     requestBody:
 *       required: false
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               generateUIDs:
 *                 type: boolean
 *                 description: "Whether to generate UIDs for finished goods (default: true)"
 *     responses:
 *       200:
 *         description: Production confirmed successfully
 *       400:
 *         description: Validation error or insufficient materials
 *       401:
 *         description: Unauthorized
 *       403:
 *         description: Forbidden (insufficient permissions)
 *       404:
 *         description: Production order not found
 */
router.post(
  '/orders/:id/confirm', // POST /api/production/orders/:id/confirm
  authenticate, // Require authentication
  requireRole(['manager', 'system_admin']), // Require role
  productionValidations.validateConfirmProduction, // Validate request
  productionControllers.confirmProduction // Confirm production controller
);

// Export router
module.exports = router;
