/**
 * Shared "start export job + poll until finished" flow used by the object,
 * repository and publication point detail pages. The page renders the
 * returned mutation/query state with `WorkflowStatus` and friends.
 */
import { useState } from "react";
import { useMutation, useQuery } from "@tanstack/react-query";
import { createExport, getExportJob, type ExportRequest } from "../api/service";

export function useExportJob(runId: string, request: ExportRequest) {
  const [jobId, setJobId] = useState<string | null>(null);

  const startMutation = useMutation({
    mutationFn: () => createExport(runId, request),
    onSuccess: (job) => setJobId(job.jobId),
  });

  const jobQuery = useQuery({
    queryKey: ["export-job", runId, jobId],
    queryFn: () => getExportJob(runId, jobId!),
    enabled: jobId !== null,
    refetchInterval: (query) => (query.state.data?.status === "running" ? 2000 : false),
  });

  // Keep the trigger disabled until the job reaches a terminal state so the
  // same export cannot be double-submitted while it is still running.
  const running =
    startMutation.isPending ||
    (jobId !== null &&
      jobQuery.data?.status !== "complete" &&
      jobQuery.data?.status !== "failed");

  return { startMutation, jobQuery, running };
}
