"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.saveVersion = void 0;
const enforceMaxVersions_1 = require("./enforceMaxVersions");
const sanitizeInternalFields_1 = __importDefault(require("../utilities/sanitizeInternalFields"));
const saveVersion = async ({ payload, collection, global, id, docWithLocales, autosave, draft, createdAt, onCreate = false, }) => {
    let entityConfig;
    let entityType;
    if (collection) {
        entityConfig = collection;
        entityType = 'collection';
    }
    if (global) {
        entityConfig = global;
        entityType = 'global';
    }
    const VersionModel = payload.versions[entityConfig.slug];
    const versionData = { ...docWithLocales };
    if (draft)
        versionData._status = 'draft';
    if (versionData._id)
        delete versionData._id;
    let existingAutosaveVersion;
    if (autosave) {
        const query = {};
        if (collection)
            query.parent = id;
        existingAutosaveVersion = await VersionModel.findOne(query, {}, { sort: { updatedAt: 'desc' } });
    }
    let result;
    const now = new Date().toISOString();
    try {
        if (autosave && (existingAutosaveVersion === null || existingAutosaveVersion === void 0 ? void 0 : existingAutosaveVersion.autosave) === true) {
            const data = {
                version: versionData,
                createdAt,
                updatedAt: now,
            };
            if (createdAt)
                data.updatedAt = createdAt;
            result = await VersionModel.findByIdAndUpdate({
                _id: existingAutosaveVersion._id,
            }, data, { new: true, lean: true });
            // Otherwise, create a new one
        }
        else {
            const data = {
                version: versionData,
                autosave: Boolean(autosave),
                updatedAt: onCreate ? createdAt : now,
                createdAt: createdAt || now,
            };
            if (collection)
                data.parent = id;
            result = await VersionModel.create(data);
        }
    }
    catch (err) {
        let errorMessage;
        if (collection)
            errorMessage = `There was an error while saving a version for the ${collection.labels.singular} with ID ${id}.`;
        if (global)
            errorMessage = `There was an error while saving a version for the global ${global.label}.`;
        payload.logger.error(errorMessage);
        payload.logger.error(err);
    }
    let max;
    if (collection && typeof collection.versions.maxPerDoc === 'number')
        max = collection.versions.maxPerDoc;
    if (global && typeof global.versions.max === 'number')
        max = global.versions.max;
    if (collection && collection.versions.maxPerDoc) {
        (0, enforceMaxVersions_1.enforceMaxVersions)({
            id,
            payload,
            Model: VersionModel,
            slug: entityConfig.slug,
            entityType,
            max,
        });
    }
    result = result.version;
    result = JSON.parse(JSON.stringify(result));
    result = (0, sanitizeInternalFields_1.default)(result);
    result.id = id;
    return result;
};
exports.saveVersion = saveVersion;
//# sourceMappingURL=saveVersion.js.map