"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getUUID = exports.replaceErrors = exports.removeFields = exports.fieldsToUnset = void 0;
const mongoose_1 = __importDefault(require("mongoose"));
const uuid_1 = require("uuid");
exports.fieldsToUnset = ['__v', 'createdAt', 'updatedAt'];
const deepCloneAndConvertMaps = (obj) => {
    if (obj instanceof Map) {
        return Object.fromEntries(obj);
    }
    if (Array.isArray(obj)) {
        return obj.map((item) => deepCloneAndConvertMaps(item));
    }
    if (Buffer.isBuffer(obj) || ArrayBuffer.isView(obj)) {
        return obj;
    }
    if (obj instanceof Date) {
        return new Date(obj.getTime());
    }
    if (obj instanceof mongoose_1.default.Types.ObjectId) {
        return obj.toString();
    }
    if (typeof obj === 'object' && obj !== null) {
        const newObj = Object.assign({}, obj);
        Object.keys(newObj).forEach((key) => {
            newObj[key] = deepCloneAndConvertMaps(newObj[key]);
        });
        return newObj;
    }
    return obj;
};
const removeFields = (document, fieldsToUnset) => {
    return document.toObject({
        transform: (_doc, ret) => {
            fieldsToUnset.forEach((field) => delete ret[field]);
            return deepCloneAndConvertMaps(ret);
        },
    });
};
exports.removeFields = removeFields;
const replaceErrors = (error, dictionary) => {
    const getValue = (d, keys) => {
        let currentValue = d;
        for (const part of keys) {
            if (currentValue && currentValue[part]) {
                currentValue = currentValue[part];
            }
            else {
                return part;
            }
        }
        return currentValue;
    };
    const refinedErrors = error.details.map((detail) => {
        const pathFull = detail.path.join('.');
        const value = getValue(dictionary, detail.path);
        return detail.message.replace(pathFull, value);
    });
    return refinedErrors.join(', ');
};
exports.replaceErrors = replaceErrors;
const getUUID = () => (0, uuid_1.v4)();
exports.getUUID = getUUID;
