// Helpers for plain JSON data (the arrangement as it is saved, merged and
// edited): records, deep equality, copies that share nothing, and the
// identity of a list item. Shared by merge.ts and edits.ts, and like them
// free of DOM and globals so the Node tests can load it.

type DataRecord = { [key: string]: unknown };

const isDataRecord = (value: unknown): value is DataRecord =>
  typeof value === "object" && value !== null && !Array.isArray(value);

const dataEqual = (a: unknown, b: unknown): boolean => {
  if (a === b) return true;
  if (Array.isArray(a) || Array.isArray(b)) {
    if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
    return a.every((item, index) => dataEqual(item, b[index]));
  }
  if (isDataRecord(a) && isDataRecord(b)) {
    const keysA = Object.keys(a);
    const keysB = Object.keys(b);
    if (keysA.length !== keysB.length) return false;
    return keysA.every((key) => key in b && dataEqual(a[key], b[key]));
  }
  return false;
};

// A copy that shares nothing with its source: the live arrangement is
// mutated in place all over the app, so a stored reference would silently
// change under us. undefined stays undefined (JSON would drop it).
const cloneData = <T>(value: T): T =>
  value === undefined ? value : (JSON.parse(JSON.stringify(value)) as T);

// Lists in the arrangement are ordered sets of ids (strings) or of small
// records that stand for one (guestOrder's entries); the record's JSON is
// its identity.
const listItemKey = (item: unknown): string =>
  typeof item === "string" ? item : JSON.stringify(item);
