import { useMutation, useQueryClient } from "@tanstack/react-query";
import { api, type ParseOptions } from "@/lib/api";
import type {
  BatchSummary as ParserBatchSummary,
  ParseResult837,
  ParseResult835,
} from "@/types";

type ParseResult = ParseResult837 | ParseResult835 | ParserBatchSummary;

/**
 * Mutation that runs an EDI file through the parser. On success, invalidates
 * every list query that might have been affected by the new batch so pages
 * showing stale data re-fetch.
 */
export function useParse(kind: "837p" | "835") {
  const qc = useQueryClient();
  return useMutation<ParseResult, Error, { file: File; options?: ParseOptions }>({
    mutationFn: (opts) => {
      const fn = kind === "837p" ? api.parse837 : api.parse835;
      return fn(opts.file, opts.options) as Promise<ParseResult>;
    },
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["batches"] });
      qc.invalidateQueries({ queryKey: ["claims"] });
      qc.invalidateQueries({ queryKey: ["remittances"] });
      qc.invalidateQueries({ queryKey: ["providers"] });
      qc.invalidateQueries({ queryKey: ["activity"] });
    },
  });
}
