import { createHash } from 'node:crypto';

export const hashJson = (obj: any) => {
  const h = createHash('sha256');

  const helper = (val: any) => {
    if (Array.isArray(val)) {
      h.update('[');
      val.forEach((v) => {
        helper(v);
        h.update(',');
      });
      h.update(']');
    } else if (val === null) {
      h.update('null');
    } else if (typeof val === 'number') {
      h.update(val.toString());
    } else if (typeof val === 'string') {
      h.update('"');
      h.update(val);
      h.update('"');
    } else {
      h.update('{');
      const keys = Object.keys(val);
      keys.sort().forEach((k) => {
        h.update(k + ':');
        helper(val[k]);
        h.update(',');
      });
      h.update('}');
    }
  };
  helper(obj);
  return h.digest('hex');
};
