/**
 * Direct Production Service Hook
 *
 * Phase 1 optimization: Call production service directly instead of through orchestrator.
 * Eliminates one network hop and reduces orchestrator load.
 */

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

export interface ProductionBatch {
  id: string;
  product_id: string;
  product_name: string;
  planned_quantity: number;
  actual_quantity?: number;
  status: 'PENDING' | 'IN_PROGRESS' | 'COMPLETED' | 'ON_HOLD' | 'CANCELLED';
  planned_start_time: string;
  planned_end_time: string;
  actual_start_time?: string;
  actual_end_time?: string;
  priority: 'LOW' | 'NORMAL' | 'HIGH' | 'URGENT';
  notes?: string;
}

export interface ProductionBatchesResponse {
  batches: ProductionBatch[];
  total_count: number;
  date: string;
}

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

/**
 * Fetch production batches by status directly from production service
 */
export const useProductionBatchesByStatus = (
  tenantId: string,
  status: string,
  options?: {
    enabled?: boolean;
    limit?: number;
  }
): UseQueryResult<ProductionBatchesResponse> => {
  const limit = options?.limit ?? 100;

  return useQuery({
    queryKey: ['production', 'batches', 'status', status, tenantId, limit],
    queryFn: async () => {
      const url = getTenantEndpoint(
        'production',
        tenantId,
        `production/batches?status=${status}&limit=${limit}`
      );
      return await apiClient.get(url);
    },
    staleTime: 30000,
    enabled: options?.enabled ?? true,
  });
};
