"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "createReportDefinitionVersion", {
    enumerable: true,
    get: function() {
        return createReportDefinitionVersion;
    }
});
const _sequelize = /*#__PURE__*/ _interop_require_default(require("sequelize"));
const _errors = require("@tamanu/errors");
const _utils = require("./utils");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
async function createReportDefinitionVersion({ store, reportSchemaStores }, reportId, definition, userId) {
    const { models: { ReportDefinition, ReportDefinitionVersion }, sequelize } = store;
    if (definition.versionNumber) {
        throw new _errors.InvalidOperationError('Cannot create a report with a version number');
    }
    const { parameters } = definition.queryOptions;
    await (0, _utils.verifyQuery)(definition.query, {
        parameters
    }, {
        reportSchemaStores,
        store
    }, definition.dbSchema);
    return sequelize.transaction({
        // Prevents race condition when determining the next version number
        isolationLevel: _sequelize.default.Transaction.ISOLATION_LEVELS.SERIALIZABLE
    }, async ()=>{
        const { name, dbSchema, ...definitionVersion } = definition;
        if (!reportId) {
            const existingDefinition = await ReportDefinition.findOne({
                where: {
                    name
                },
                attributes: [
                    'id'
                ]
            });
            if (existingDefinition) {
                throw new _errors.InvalidOperationError('Report name already exists');
            }
        }
        const reportDefinitionId = reportId || (await ReportDefinition.create({
            name,
            dbSchema
        })).id;
        const latestVersion = await ReportDefinitionVersion.findOne({
            where: {
                reportDefinitionId: reportId
            },
            attributes: [
                'versionNumber'
            ],
            order: [
                [
                    'versionNumber',
                    'DESC'
                ]
            ]
        });
        const nextVersionNumber = (latestVersion?.versionNumber || 0) + 1;
        const version = await ReportDefinitionVersion.create({
            ...definitionVersion,
            userId,
            versionNumber: nextVersionNumber,
            reportDefinitionId
        });
        return {
            name,
            reportDefinitionId,
            ...version.get({
                plain: true
            })
        };
    });
}

//# sourceMappingURL=createReportDefinitionVersion.js.map