import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { api } from '@/api/client';
import { keys } from '@/api/workflows';
import type { ExecutionDetail, ExecutionSummary, RetentionInfo } from '@/types';

/**
 * Run history, the inspector, and retries.
 *
 * History is the one screen where stale data is actively misleading — a run
 * that finished ten seconds ago should not still say "running" — so these
 * queries do not share the app's default 30-second staleTime.
 */

interface HistoryResponse {
  data: ExecutionSummary[];
  meta?: { total?: number; totalPages?: number };
  retention?: RetentionInfo;
}

export interface HistoryFilters {
  workflow: number | null;
  status: string;
  page: number;
}

export function useExecutions({ workflow, status, page }: HistoryFilters) {
  return useQuery({
    queryKey: keys.executions(workflow, status, page),
    queryFn: async () => {
      const params = new URLSearchParams({ page: String(page), per_page: '20' });

      if (workflow !== null) {
        params.set('workflow', String(workflow));
      }

      if (status !== '') {
        params.set('status', status);
      }

      const response = (await api.get<ExecutionSummary[]>(
        `/executions?${params.toString()}`,
      )) as HistoryResponse;

      return {
        items: response.data,
        total: response.meta?.total ?? response.data.length,
        totalPages: response.meta?.totalPages ?? 1,
        retention: response.retention ?? { days: null, expired: 0 },
      };
    },
    staleTime: 0,
  });
}

export function useExecution(id: number | null) {
  return useQuery({
    queryKey: keys.execution(id ?? 0),
    queryFn: async () => (await api.get<ExecutionDetail>(`/executions/${id}`)).data,
    enabled: id !== null,
    staleTime: 0,
  });
}

/** Run a finished execution again. The original stays in the history. */
export function useRetryExecution() {
  const client = useQueryClient();

  return useMutation({
    mutationFn: async (id: number) =>
      (await api.post<{ executionId: number; status: string; statusLabel: string }>(
        `/executions/${id}/retry`,
      )).data,
    onSuccess: () => {
      // A retry adds a run and may change the workflow's counts, so both the
      // history and the workflow list are now out of date.
      void client.invalidateQueries({ queryKey: ['flowwp', 'executions'] });
      void client.invalidateQueries({ queryKey: keys.workflows });
    },
  });
}
