import type {
  BatchDraft,
  BatchImportResult,
} from "./mutationTypes";

let draftSequence = 0;

export function createBatchDraft<TMetadata>(
  file: File,
  metadata: TMetadata,
): BatchDraft<TMetadata> {
  draftSequence += 1;
  return {
    key: `${Date.now()}-${draftSequence}`,
    file,
    metadata,
  };
}

export function applyBatchResult<TMetadata>(
  drafts: BatchDraft<TMetadata>[],
  result: BatchImportResult,
): BatchDraft<TMetadata>[] {
  if (drafts.length !== result.items.length) {
    throw new Error("批量结果无法对应原始文件");
  }
  return drafts.map((draft, index) => ({
    ...draft,
    result: result.items[index],
  }));
}

export function retainFailedDrafts<TMetadata>(
  drafts: BatchDraft<TMetadata>[],
): BatchDraft<TMetadata>[] {
  return drafts
    .filter((draft) => draft.result?.success === false)
    .map(({ result: _result, ...draft }) => draft);
}

export function createExclusiveRunner() {
  let running = false;
  return async function run<T>(operation: () => Promise<T>): Promise<T | undefined> {
    if (running) return undefined;
    running = true;
    try {
      return await operation();
    } finally {
      running = false;
    }
  };
}
