export interface StableStringEntry {
  id: string;
  value: string;
}

const generateStableStringEntryId = (): string => {
  if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
    return crypto.randomUUID();
  }

  return `entry-${Math.random().toString(36).slice(2)}`;
};

export const createStableStringEntry = (value: string): StableStringEntry => ({
  id: generateStableStringEntryId(),
  value,
});

export const reconcileStableStringEntries = (
  previousEntries: StableStringEntry[],
  nextValues: string[],
): StableStringEntry[] => {
  const available = [...previousEntries];

  return nextValues.map((value) => {
    const matchIndex = available.findIndex((entry) => entry.value === value);
    if (matchIndex >= 0) {
      const [existing] = available.splice(matchIndex, 1) as [StableStringEntry];
      return existing;
    }

    return createStableStringEntry(value);
  });
};
