/**
 * Orchestrator React Query hooks
 */
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import * as orchestratorService from '../services/orchestrator';
import {
  OrchestratorConfig,
  OrchestratorStatus,
  OrchestratorWorkflowResponse,
  WorkflowExecutionDetail,
  WorkflowExecutionSummary
} from '../types/orchestrator';

// ============================================================================
// QUERIES
// ============================================================================

export const useOrchestratorStatus = (tenantId: string) => {
  return useQuery<OrchestratorStatus>({
    queryKey: ['orchestrator', 'status', tenantId],
    queryFn: () => orchestratorService.getOrchestratorStatus(tenantId),
    enabled: !!tenantId,
    refetchInterval: 30000, // Refresh every 30s
  });
};

export const useOrchestratorConfig = (tenantId: string) => {
  return useQuery<OrchestratorConfig>({
    queryKey: ['orchestrator', 'config', tenantId],
    queryFn: () => orchestratorService.getOrchestratorConfig(tenantId),
    enabled: !!tenantId,
  });
};

export const useLatestWorkflowExecution = (tenantId: string) => {
  return useQuery<WorkflowExecutionDetail | null>({
    queryKey: ['orchestrator', 'executions', 'latest', tenantId],
    queryFn: () => orchestratorService.getLatestWorkflowExecution(tenantId),
    enabled: !!tenantId,
    refetchInterval: (data) => {
      // If running, poll more frequently
      return data?.status === 'running' ? 5000 : 60000;
    },
  });
};

export const useWorkflowExecutions = (
  tenantId: string,
  params?: { limit?: number; offset?: number; status?: string }
) => {
  return useQuery<WorkflowExecutionSummary[]>({
    queryKey: ['orchestrator', 'executions', tenantId, params],
    queryFn: () => orchestratorService.listWorkflowExecutions(tenantId, params),
    enabled: !!tenantId,
  });
};

export const useWorkflowExecution = (tenantId: string, executionId: string) => {
  return useQuery<WorkflowExecutionDetail>({
    queryKey: ['orchestrator', 'execution', tenantId, executionId],
    queryFn: () => orchestratorService.getWorkflowExecution(tenantId, executionId),
    enabled: !!tenantId && !!executionId,
    refetchInterval: (data) => {
      // If running, poll more frequently
      return data?.status === 'running' ? 3000 : false;
    },
  });
};

// ============================================================================
// MUTATIONS
// ============================================================================

export const useRunDailyWorkflow = (
  options?: Parameters<typeof useMutation>[0]
) => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (tenantId: string) =>
      orchestratorService.runDailyWorkflow(tenantId),
    onSuccess: (_, tenantId) => {
      // Invalidate queries to refresh dashboard data after workflow execution
      queryClient.invalidateQueries({ queryKey: ['procurement', 'plans'] });
      queryClient.invalidateQueries({ queryKey: ['production', 'batches'] });
      queryClient.invalidateQueries({ queryKey: ['forecasts'] });
      // Also invalidate dashboard queries to refresh stats
      queryClient.invalidateQueries({ queryKey: ['dashboard', 'stats'] });
      queryClient.invalidateQueries({ queryKey: ['dashboard'] });
      // Invalidate orchestrator queries
      queryClient.invalidateQueries({ queryKey: ['orchestrator', 'executions'] });
      queryClient.invalidateQueries({ queryKey: ['orchestrator', 'status'] });
    },
    ...options,
  });
};

export const useTestWorkflow = (
  options?: Parameters<typeof useMutation>[0]
) => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (tenantId: string) =>
      orchestratorService.testWorkflow(tenantId),
    onSuccess: (_, tenantId) => {
      queryClient.invalidateQueries({ queryKey: ['orchestrator', 'executions'] });
    },
    ...options,
  });
};

export const useUpdateOrchestratorConfig = (
  options?: Parameters<typeof useMutation>[0]
) => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ tenantId, config }: { tenantId: string; config: Partial<OrchestratorConfig> }) =>
      orchestratorService.updateOrchestratorConfig(tenantId, config),
    onSuccess: (_, { tenantId }) => {
      queryClient.invalidateQueries({ queryKey: ['orchestrator', 'config', tenantId] });
    },
    ...options,
  });
};

export const useCancelWorkflowExecution = (
  options?: Parameters<typeof useMutation>[0]
) => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ tenantId, executionId }: { tenantId: string; executionId: string }) =>
      orchestratorService.cancelWorkflowExecution(tenantId, executionId),
    onSuccess: (_, { tenantId, executionId }) => {
      queryClient.invalidateQueries({ queryKey: ['orchestrator', 'execution', tenantId, executionId] });
      queryClient.invalidateQueries({ queryKey: ['orchestrator', 'executions', tenantId] });
    },
    ...options,
  });
};

export const useRetryWorkflowExecution = (
  options?: Parameters<typeof useMutation>[0]
) => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ tenantId, executionId }: { tenantId: string; executionId: string }) =>
      orchestratorService.retryWorkflowExecution(tenantId, executionId),
    onSuccess: (_, { tenantId, executionId }) => {
      queryClient.invalidateQueries({ queryKey: ['orchestrator', 'execution', tenantId, executionId] });
      queryClient.invalidateQueries({ queryKey: ['orchestrator', 'executions', tenantId] });
    },
    ...options,
  });
};
