const atpService = require('../services/atpService');
const { sendResponse, sendError } = require('../utils/response');
const asyncHandler = require('../middlewares/asyncHandler');

/**
 * Get Available to Promise (ATP) stock for a material
 * GET /inventory/atp/stock?materialId=1&plantId=1&storageLocation=SL01
 */
exports.getStock = asyncHandler(async (req, res) => {
  const { materialId, plantId, storageLocation } = req.query;

  if (!materialId || !plantId) {
    return sendError(res, 'Material ID and Plant ID are required', 400);
  }

  try {
    const stockInfo = await atpService.getAvailableStock(
      parseInt(materialId),
      parseInt(plantId),
      storageLocation || null
    );

    sendResponse(res, 200, true, 'ATP stock retrieved successfully', {
      material_id: parseInt(materialId),
      plant_id: parseInt(plantId),
      storage_location: storageLocation || null,
      available_quantity: stockInfo.available,
      receipts: stockInfo.receipts,
      issues: stockInfo.issues,
      pending_quantity: stockInfo.pendingQuantity,
      reserved_quantity: stockInfo.reserved,
      locations: stockInfo.availableLocations || [] // Include location-wise stock details
    });
  } catch (error) {
    console.error('Error getting ATP stock:', error);
    sendError(res, error.message || 'Failed to get ATP stock', 500);
  }
});

/**
 * Check ATP for multiple materials
 * POST /inventory/atp/check
 * Body: { items: [{ materialId, plantId, quantity, storageLocation }] }
 */
exports.checkATP = asyncHandler(async (req, res) => {
  const { items } = req.body;

  if (!items || !Array.isArray(items) || items.length === 0) {
    return sendError(res, 'Items array is required', 400);
  }

  try {
    const results = await atpService.checkATP(items);
    sendResponse(res, 200, true, 'ATP check completed successfully', results);
  } catch (error) {
    console.error('Error checking ATP:', error);
    sendError(res, error.message || 'Failed to check ATP', 500);
  }
});

