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

export interface UploadDocumentVars {
  stepId: number;
  file: File;
  /** Progress callback (0–100) the uploader wires to its progress bar. */
  onProgress?: (percent: number) => void;
}

/**
 * Uploads a manual step's document (url → PUT bytes → confirm) and moves it to `in_review`. Progress
 * is reported through `vars.onProgress` (React Query can't stream it), so the `<DocumentUpload>`
 * component owns the bar while the mutation owns the request + cache invalidation — the checklist then
 * shows the step `in_review` from cache with no manual refetch.
 */
export function useUploadVerificationDocument() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ stepId, file, onProgress }: UploadDocumentVars): Promise<VerificationDocument> =>
      verificationApi.uploadStepDocument(stepId, file, onProgress),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: verificationKeys.status() });
    },
  });
}
