/**
 * Direct Inventory Service Hook
 *
 * Phase 1 optimization: Call inventory service directly instead of through orchestrator.
 * Eliminates duplicate fetches and reduces orchestrator load.
 */

import { useQuery, UseQueryResult } from '@tanstack/react-query';
import { getTenantEndpoint } from '../../config/services';
import { apiClient } from '../client';

export interface StockStatus {
  category: string;
  in_stock: number;
  low_stock: number;
  out_of_stock: number;
  total: number;
}

export interface InventoryOverview {
  out_of_stock_count: number;
  low_stock_count: number;
  adequate_stock_count: number;
  total_ingredients: number;
  total_value?: number;
  tenant_id: string;
  timestamp: string;
}

export interface SustainabilityWidget {
  waste_reduction_percentage: number;
  local_sourcing_percentage: number;
  seasonal_usage_percentage: number;
  carbon_footprint_score?: number;
}

/**
 * Fetch inventory overview directly from inventory service
 */
export const useInventoryOverview = (
  tenantId: string,
  options?: {
    enabled?: boolean;
    refetchInterval?: number;
  }
): UseQueryResult<InventoryOverview> => {
  return useQuery({
    queryKey: ['inventory', 'overview', tenantId],
    queryFn: async () => {
      const url = getTenantEndpoint('inventory', tenantId, 'inventory/dashboard/overview');
      return await apiClient.get(url);
    },
    staleTime: 30000, // 30s cache
    refetchInterval: options?.refetchInterval,
    enabled: options?.enabled ?? true,
  });
};

/**
 * Fetch stock status by category directly from inventory service
 */
export const useStockStatusByCategory = (
  tenantId: string,
  options?: {
    enabled?: boolean;
  }
): UseQueryResult<StockStatus[]> => {
  return useQuery({
    queryKey: ['inventory', 'stock-status', tenantId],
    queryFn: async () => {
      const url = getTenantEndpoint('inventory', tenantId, 'inventory/dashboard/stock-status');
      return await apiClient.get(url);
    },
    staleTime: 30000,
    enabled: options?.enabled ?? true,
  });
};

/**
 * Fetch sustainability widget data directly from inventory service
 */
export const useSustainabilityWidget = (
  tenantId: string,
  options?: {
    enabled?: boolean;
  }
): UseQueryResult<SustainabilityWidget> => {
  return useQuery({
    queryKey: ['inventory', 'sustainability', 'widget', tenantId],
    queryFn: async () => {
      const url = getTenantEndpoint('inventory', tenantId, 'sustainability/widget');
      return await apiClient.get(url);
    },
    staleTime: 60000, // 60s cache (changes less frequently)
    enabled: options?.enabled ?? true,
  });
};
