import { useMutation, useQueryClient } from '@tanstack/react-query';
import { verificationApi } from '../apis';
import { verificationKeys } from '../keys';
import type { DecideStepInput, DecideStepResult } from '../types';

export interface DecideStepVars {
  stepId: number;
  /** The case this step belongs to — used to invalidate exactly that case on success. */
  nurseVerificationId: number;
  input: DecideStepInput;
}

/**
 * Approve or reject a manual step. On approving a credential-bearing step the (encrypted) credential is
 * recorded server-side and its `credentialId` comes back; a reject requires `input.rejectionReason`. On
 * success we invalidate the case (its steps re-render) and the queue (the aggregate/counts may have moved,
 * or the case may have dropped off). A domain 4xx (missing reason, holder-name mismatch) surfaces to the
 * caller's `onError`.
 */
export function useDecideStep() {
  const queryClient = useQueryClient();
  return useMutation<DecideStepResult, unknown, DecideStepVars>({
    mutationFn: ({ stepId, input }) => verificationApi.decideStep(stepId, input),
    onSuccess: (_result, { nurseVerificationId }) => {
      queryClient.invalidateQueries({ queryKey: verificationKeys.adminCase(nurseVerificationId) });
      queryClient.invalidateQueries({ queryKey: verificationKeys.adminQueues() });
    },
  });
}
