/**
 * Cleans all JavaScript referneces and prototypes from Object
 * so it can be stored in Firestore.
 * @param input The JS Object to clean
 * @param keepDocumentReferenceId Should we keep reference ids for relationships
 */
export default async function cleanObjectOfReferences(input, keepDocumentReferenceId = false) {
  var _a, _b, _c, _d, _e;
  const data = input;
  for (const key of Object.keys(input)) {
    const value = input[key];
    if (!value)
      continue;
    try {
      if (((_a = value === null || value === void 0 ? void 0 : value.constructor) === null || _a === void 0 ? void 0 : _a.name) === "Object") {
        data[key] = await cleanObjectOfReferences(value);
      }
      else if (((_b = value === null || value === void 0 ? void 0 : value.constructor) === null || _b === void 0 ? void 0 : _b.name) === "DocumentReference") {
        keepDocumentReferenceId
          ? (data[key] = { id: value.id })
          : delete data[key];
      }
      else if (((_c = value === null || value === void 0 ? void 0 : value.constructor) === null || _c === void 0 ? void 0 : _c.name) === "Timestamp") {
        data[key] = value.toDate();
      }
      else if (((_d = value === null || value === void 0 ? void 0 : value.constructor) === null || _d === void 0 ? void 0 : _d.name) === "Array") {
        const cleanArray = [];
        for (const item of data[key]) {
          cleanArray.push(await cleanObjectOfReferences(item));
        }
        data[key] = cleanArray;
      }
      else if (typeof value === "object" &&
        ((_e = value === null || value === void 0 ? void 0 : value.constructor) === null || _e === void 0 ? void 0 : _e.name) !== "Date") {
        data[key] = await cleanObjectOfReferences(JSON.parse(JSON.stringify(value)));
      }
    }
    catch (err) {
      delete data[key];
    }
  }
  return JSON.parse(JSON.stringify(data));
}
