"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.isValidId = exports.normalizeObject = exports.renameKeys = void 0;
const mongoose_1 = __importDefault(require("mongoose"));
const renameKeys = (obj, oldName, newName) => {
    const keyValues = Object.keys(obj).map((key) => {
        let newKey;
        if (key === oldName) {
            newKey = newName;
        }
        else {
            newKey = key;
        }
        if (Array.isArray(obj[key])) {
            obj[key] = obj[key].map(obj => (0, exports.renameKeys)(obj, oldName, newName));
        }
        if ((obj[key] instanceof Object) && !(obj[key] instanceof Date) && !(obj[key] instanceof mongoose_1.default.Types.ObjectId)) {
            obj[key] = (0, exports.renameKeys)(obj[key], oldName, newName);
        }
        return {
            [newKey]: obj[key]
        };
    });
    return Object.assign({}, ...keyValues);
};
exports.renameKeys = renameKeys;
const normalizeObject = (obj, oldName = '_id', newName = 'id') => {
    const keyValues = Object.keys(obj).map((key) => {
        if (key === '__v') {
            delete obj[key];
            return;
        }
        let newKey;
        if (key === oldName) {
            newKey = newName;
        }
        else {
            newKey = key;
        }
        if (Array.isArray(obj[key])) {
            obj[key] = obj[key].map((nestedObj) => (0, exports.normalizeObject)(nestedObj, oldName, newName));
            return { [newKey]: obj[key] };
        }
        if ((obj[key] instanceof Object) && !(obj[key] instanceof Date) && !(obj[key] instanceof mongoose_1.default.Types.ObjectId)) {
            obj[key] = (0, exports.normalizeObject)(obj[key], oldName, newName);
            return { [newKey]: obj[key] };
        }
        return {
            [newKey]: obj[key]
        };
    });
    return Object.assign({}, ...keyValues);
};
exports.normalizeObject = normalizeObject;
const mongoValidator = (id) => {
    if (mongoose_1.default.Types.ObjectId.isValid(id)) {
        return (String)(new mongoose_1.default.Types.ObjectId(id)) === id;
    }
    return false;
};
const isValidId = (id) => {
    if (!id) {
        return false;
    }
    if (typeof id !== 'string') {
        id = id.toString();
    }
    const regex = new RegExp(/^[a-f\d]{24}$/i);
    const regexResult = regex.test(id);
    return regexResult && mongoValidator(id);
};
exports.isValidId = isValidId;
