// =============================================================================
// 📊 ХУК ДЛЯ ВАЛИДАЦИИ ОСТАТКОВ
// =============================================================================

import { useCallback } from 'react'

import type { 
  FulfillmentConsumableProduct,
  StockCalculation,
  StockValidationResult, 
} from '../types'

export function useStockValidation() {
  // Расчет остатков товара
  const calculateStock = useCallback((product: FulfillmentConsumableProduct): StockCalculation => {
    const totalStock = product.stock || product.quantity || 0
    const orderedStock = product.ordered || 0
    const availableStock = totalStock - orderedStock

    return {
      totalStock,
      orderedStock,
      availableStock,
    }
  }, [])

  // Валидация запрашиваемого количества
  const validateQuantity = useCallback((
    product: FulfillmentConsumableProduct, 
    requestedQuantity: number,
  ): StockValidationResult => {
    const { availableStock } = calculateStock(product)

    if (requestedQuantity <= 0) {
      return {
        isValid: true,
        availableStock,
        requestedQuantity,
      }
    }

    if (requestedQuantity > availableStock) {
      return {
        isValid: false,
        availableStock,
        requestedQuantity,
        error: `❌ Недостаточно остатков!\nДоступно: ${availableStock} шт.\nЗапрашивается: ${requestedQuantity} шт.`,
      }
    }

    return {
      isValid: true,
      availableStock,
      requestedQuantity,
    }
  }, [calculateStock])

  // Определение статуса остатков для UI
  const getStockStatus = useCallback((product: FulfillmentConsumableProduct): 'out_of_stock' | 'low_stock' | 'in_stock' => {
    const { availableStock } = calculateStock(product)

    if (availableStock <= 0) {
      return 'out_of_stock'
    } else if (availableStock <= 10) {
      return 'low_stock'
    }
    
    return 'in_stock'
  }, [calculateStock])

  return {
    calculateStock,
    validateQuantity,
    getStockStatus,
  }
}