/**
 * Inventory Reconciliation Controllers
 * Request handlers for inventory reconciliation endpoints
 */

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

/**
 * Get reconciliation report
 * Shows all inventory discrepancies
 */
const getReconciliationReport = asyncHandler(async (req, res) => {
  const { product_id } = req.query;
  const productId = product_id ? parseInt(product_id) : null;

  const report = await inventoryService.getReconciliationReport(productId);

  logger.info('Reconciliation report requested', {
    productId,
    discrepanciesFound: report.total_discrepancies,
  });

  return successResponse(res, report, 'Reconciliation report generated successfully');
});

/**
 * Check for discrepancies
 * Identifies inventory discrepancies without fixing them
 */
const checkDiscrepancies = asyncHandler(async (req, res) => {
  const { product_id } = req.query;
  const productId = product_id ? parseInt(product_id) : null;

  const discrepancies = await inventoryService.checkDiscrepancies(productId);

  logger.info('Discrepancy check requested', {
    productId,
    discrepanciesFound: discrepancies.length,
  });

  return successResponse(res, {
    discrepancies,
    count: discrepancies.length,
  }, 'Discrepancy check completed');
});

/**
 * Auto-reconcile discrepancies
 * Automatically fixes discrepancies using UID count as source of truth
 */
const autoReconcile = asyncHandler(async (req, res) => {
  const { product_id } = req.body;
  const productId = product_id ? parseInt(product_id) : null;

  logger.info('Auto-reconciliation started', { productId });

  const results = await inventoryService.autoReconcile(productId);

  logger.info('Auto-reconciliation completed', {
    productId,
    fixed: results.fixed?.length || 0,
    errors: results.errors?.length || 0,
    skipped: results.skipped?.length || 0,
  });

  return successResponse(res, results, 'Reconciliation completed successfully');
});

module.exports = {
  getReconciliationReport,
  checkDiscrepancies,
  autoReconcile,
};

