/**
 * Inventory Items Controllers (UID-Based)
 * Request handlers for UID-based inventory item operations
 */

// Import inventory service functions
const inventoryService = require('../services');
// Import async handler wrapper
const asyncHandler = require('../../../middlewares/asyncHandler');
// Import response helpers
const { success: successResponse } = require('../../../utils/response');
// Import logger
const logger = require('../../../utils/logger');

/**
 * Create inventory item
 * Creates a new inventory item with UID and barcode
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const createInventoryItem = asyncHandler(async (req, res) => {
  // Extract item data from request body
  const itemData = req.body; // Get item data
  // Get user ID from request (from authentication middleware)
  const userId = req.user.id; // Get authenticated user ID
  
  // Create inventory item using service
  const inventoryItem = await inventoryService.createInventoryItem(itemData, userId); // Create item
  
  // Log inventory item creation
  logger.info('Inventory item created', {
    itemId: inventoryItem.id,
    uid: inventoryItem.uid,
    productId: itemData.product_id,
    variantId: itemData.variant_id,
    source: itemData.source,
    userId, // Log user ID
  });
  
  // Return success response with inventory item data
  return successResponse(res, inventoryItem, 'Inventory item created successfully', 201); // Return success response
});

/**
 * Get inventory item by UID
 * Retrieves an inventory item by its UID or barcode
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const getInventoryItemByUID = asyncHandler(async (req, res) => {
  // Extract UID/barcode from request params
  const { uid } = req.params; // Get UID/barcode
  
  // Get inventory item using service
  const inventoryItem = await inventoryService.getInventoryItemByUID(uid); // Get item
  
  // Return success response with inventory item data
  return successResponse(res, inventoryItem, 'Inventory item retrieved successfully'); // Return success response
});

/**
 * Update inventory item status
 * Updates the status of an inventory item
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const updateInventoryItemStatus = asyncHandler(async (req, res) => {
  // Extract UID/barcode from request params
  const { uid } = req.params; // Get UID/barcode
  // Extract new status and reason from request body
  const { status, reason } = req.body; // Get status and reason
  // Get user ID from request (from authentication middleware)
  const userId = req.user.id; // Get authenticated user ID
  
  // Update inventory item status using service
  const inventoryItem = await inventoryService.updateInventoryItemStatus(uid, status, userId, reason); // Update status
  
  // Log status update
  logger.info('Inventory item status updated', {
    itemId: inventoryItem.id,
    uid,
    status,
    reason,
    userId, // Log user ID
  });
  
  // Return success response with updated inventory item data
  return successResponse(res, inventoryItem, 'Inventory item status updated successfully'); // Return success response
});

/**
 * Scan inventory item
 * Scans an inventory item by UID or barcode and returns details with QR code
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const scanInventoryItem = asyncHandler(async (req, res) => {
  // Extract UID/barcode from request params
  const { uid } = req.params; // Get UID/barcode
  
  // Scan inventory item using service (returns item with QR code)
  const scannedItem = await inventoryService.scanInventoryItem(uid); // Scan item
  
  // Log scan operation
  logger.info('Inventory item scanned', {
    uid,
    itemId: scannedItem.id,
  });
  
  // Return success response with scanned item data (includes QR code)
  return successResponse(res, scannedItem, 'Inventory item scanned successfully'); // Return success response
});

/**
 * List inventory items
 * Retrieves paginated list of inventory items with filters
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const listInventoryItems = asyncHandler(async (req, res) => {
  // Extract query parameters
  const {
    page = 1, // Page number (default: 1)
    limit = 10, // Items per page (default: 10)
    product_id, // Filter by product ID
    variant_id, // Filter by variant ID
    status, // Filter by status
    source, // Filter by source
    source_reference_id, // Filter by source_reference_id (GRN ID or Production Order ID)
    uid, // Filter by UID (search)
    barcode, // Filter by barcode (search)
  } = req.query; // Extract query parameters
  
  // Build options object
  const options = {
    page: parseInt(page), // Convert to integer
    limit: parseInt(limit), // Convert to integer
    productId: product_id ? parseInt(product_id) : null, // Convert to integer if provided
    variantId: variant_id ? parseInt(variant_id) : null, // Convert to integer if provided
    status: status || null, // Status filter
    source: source || null, // Source filter
    sourceReferenceId: source_reference_id ? parseInt(source_reference_id) : null, // Source reference ID filter
    uid: uid ? String(uid).trim() : null, // UID search filter
    barcode: barcode ? String(barcode).trim() : null, // Barcode search filter
  };
  
  // List inventory items using service
  const result = await inventoryService.listInventoryItems(options); // List items
  
  // Return success response with items and pagination
  return successResponse(res, result, 'Inventory items retrieved successfully'); // Return success response
});

// Export controllers
module.exports = {
  createInventoryItem, // Create inventory item controller
  getInventoryItemByUID, // Get inventory item by UID controller
  updateInventoryItemStatus, // Update inventory item status controller
  scanInventoryItem, // Scan inventory item controller
  listInventoryItems, // List inventory items controller
};

