'use client';

import { useMutation, useQueryClient } from '@tanstack/react-query';

import { completeBootstrapSetup, completeSetupRun, saveSetupStep, startSetupRun } from './service';
import { setupKeys } from './queries';
import type { CompleteBootstrapSetupPayload, SaveSetupStepPayload } from './types';

function useInvalidateSetupRun() {
  const queryClient = useQueryClient();

  return () => {
    queryClient.invalidateQueries({ queryKey: setupKeys.run() });
    queryClient.invalidateQueries({ queryKey: [...setupKeys.all, 'bootstrap'] });
    queryClient.invalidateQueries({ queryKey: setupKeys.report() });
    queryClient.invalidateQueries({ queryKey: setupKeys.bootstrapStatus() });
  };
}

export function useStartSetupRun() {
  const invalidate = useInvalidateSetupRun();

  return useMutation({
    mutationFn: () => startSetupRun(),
    onSuccess: invalidate
  });
}

export function useSaveSetupStep() {
  const invalidate = useInvalidateSetupRun();

  return useMutation({
    mutationFn: (payload: SaveSetupStepPayload) => saveSetupStep(payload),
    onSuccess: invalidate
  });
}

export function useCompleteSetupRun() {
  const invalidate = useInvalidateSetupRun();

  return useMutation({
    mutationFn: (report: Record<string, unknown>) => completeSetupRun(report),
    onSuccess: invalidate
  });
}

export function useCompleteBootstrapSetup() {
  const invalidate = useInvalidateSetupRun();

  return useMutation({
    mutationFn: (input: CompleteBootstrapSetupPayload) => completeBootstrapSetup(input),
    onSuccess: invalidate
  });
}
