import * as api from "@client/api";
import { useCallback, useState } from "react";
import { toast } from "sonner";

export function useCoverLetterGeneration(
  onJobUpdated: () => void | Promise<void>,
) {
  const [inFlight, setInFlight] = useState(false);

  const generateForJob = useCallback(
    async (jobId: string) => {
      setInFlight(true);
      try {
        const res = await api.runJobAction({
          action: "generate_cover_letter",
          jobIds: [jobId],
        });
        const r = res.results.find((entry) => entry.jobId === jobId);
        if (!r?.ok) {
          toast.error(r?.error.message ?? "Could not generate cover letter");
          return;
        }
        toast.success("Cover letter saved on this job");
        await onJobUpdated();
      } catch (e) {
        toast.error(
          e instanceof Error ? e.message : "Could not generate cover letter",
        );
      } finally {
        setInFlight(false);
      }
    },
    [onJobUpdated],
  );

  return { generateForJob, inFlight };
}
