/**
 * Stock Checking Service
 * Provides real-time stock availability checking for POS
 */

const { Inventory, InventoryItem, Product } = require('../../../models'); // ProductVariant removed
const { NotFoundError, ValidationError } = require('../../../utils/errors');
const { Op } = require('sequelize');
const logger = require('../../../utils/logger');

/**
 * Get stock availability for a product (variants removed)
 * @param {number} productId - Product ID
 * @returns {Promise<Object>} Availability data
 */
const getProductAvailability = async (productId) => {
  // Validate product exists
  const product = await Product.findByPk(productId);
  if (!product) {
    throw new NotFoundError('Product not found');
  }

  // Get quantity-based inventory (variants removed - no variant_id filtering)
  const inventory = await Inventory.findOne({
    where: {
      product_id: productId,
      // variant_id removed - variants no longer exist
    },
  });

  // Get UID-based inventory counts (variants removed - no variant_id filtering)
  const inStockCount = await InventoryItem.count({
    where: {
      product_id: productId,
      status: 'IN_STOCK',
      // variant_id removed - variants no longer exist
    },
  });

  // Get reserved count (variants removed - no variant_id filtering)
  const reservedCount = await InventoryItem.count({
    where: {
      product_id: productId,
      status: 'RESERVED',
      // variant_id removed - variants no longer exist
    },
  });

  // Quantity-based available (from Inventory table) - PRIMARY source
  const quantityBased = parseFloat(inventory?.quantity || 0);

  // UID-based available (count of IN_STOCK items) - SECONDARY check for validation
  const uidBased = inStockCount;

  // Use quantity-based inventory as the primary source of truth
  // The Inventory table quantity is the authoritative source
  // UID-based count is only used for validation/warnings, not for availability calculation
  const availableQty = product.track_inventory 
    ? quantityBased  // Use quantity-based inventory (from Inventory table)
    : quantityBased; // If not tracking inventory, still return quantity (for non-tracked items)

  // Log discrepancy warning if there's a significant difference between quantity-based and UID-based
  // This helps identify data inconsistencies without blocking sales
  if (product.track_inventory && quantityBased > 0 && uidBased > 0 && Math.abs(quantityBased - uidBased) > 1) {
    logger.warn(`Inventory quantity discrepancy detected: product_id=${productId}, quantity_based=${quantityBased}, uid_based=${uidBased}`);
  }

  return {
    product_id: productId,
    // variant_id removed - variants no longer exist
    available_qty: availableQty,
    reserved_qty: reservedCount,
    quantity_based: quantityBased,
    uid_based: uidBased,
    total_qty: availableQty + reservedCount,
    reorder_level: parseFloat(inventory?.reorder_level || 0),
    track_inventory: product.track_inventory,
  };
};

/**
 * Bulk check stock availability for multiple products (variants removed)
 * @param {Array} items - Array of {product_id, quantity}
 * @returns {Promise<Array>} Availability results
 */
const bulkCheckStock = async (items) => {
  if (!Array.isArray(items) || items.length === 0) {
    throw new ValidationError('Items array is required and cannot be empty');
  }

  const results = [];

  for (const item of items) {
    const { product_id, quantity = 0 } = item; // variant_id removed

    if (!product_id || quantity <= 0) {
      results.push({
        product_id,
        // variant_id removed - variants no longer exist
        requested: quantity,
        available: 0,
        shortfall: quantity,
        status: 'INVALID',
        error: 'Invalid product_id or quantity',
      });
      continue;
    }

    try {
      const availability = await getProductAvailability(product_id); // variant_id removed
      const requested = parseFloat(quantity);
      const available = availability.available_qty;
      const shortfall = Math.max(0, requested - available);
      const status = available >= requested ? 'IN_STOCK' : (available > 0 ? 'PARTIAL' : 'OUT_OF_STOCK');

      results.push({
        product_id,
        // variant_id removed - variants no longer exist
        requested,
        available,
        reserved: availability.reserved_qty,
        shortfall,
        status,
        reorder_level: availability.reorder_level,
      });
    } catch (error) {
      results.push({
        product_id,
        // variant_id removed - variants no longer exist
        requested: quantity,
        available: 0,
        shortfall: quantity,
        status: 'ERROR',
        error: error.message,
      });
    }
  }

  return results;
};

module.exports = {
  getProductAvailability,
  bulkCheckStock,
};

