"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.headlessModel = void 0;
const typeorm_1 = require("typeorm");
const shell_1 = require("@things-factory/shell");
const process_1 = require("../../service/process/process");
const process_history_1 = require("../../service/process/process-history");
const headlessModel = async (target, draft = false) => {
    var { domain, id, model, name } = target || {};
    if (model) {
        if (typeof model == 'string') {
            model = JSON.parse(model);
        }
        else if (typeof model !== 'object') {
            throw 'model should be a string or object';
        }
    }
    else {
        if (id) {
            var process = await (0, shell_1.getRepository)(process_1.Process).findOne({
                where: { domain: { id: (0, typeorm_1.In)([domain.id, domain.parentId].filter(Boolean)) }, id }
            });
        }
        else if (name) {
            var process = await (0, shell_1.getRepository)(process_1.Process).findOne({
                where: { domain: { id: (0, typeorm_1.In)([domain.id, domain.parentId].filter(Boolean)) }, name }
            });
        }
        else {
            throw 'parameter model or id mandatory';
        }
        if (!draft && process) {
            const latestReleased = process.state == 'released'
                ? process
                : await (0, shell_1.getRepository)(process_history_1.ProcessHistory)
                    .createQueryBuilder('history')
                    .where('history.originalId = :originalId', { originalId: process.id })
                    .orderBy('history.version', 'DESC')
                    .limit(1)
                    .getOne();
            model = (latestReleased || process).model;
        }
        else {
            model = process.model;
        }
        model = JSON.parse(model);
    }
    return {
        base: (0, shell_1.getContextPath)(domain === null || domain === void 0 ? void 0 : domain.subdomain) + (domain ? '/' : ''),
        model,
        process
    };
};
exports.headlessModel = headlessModel;
//# sourceMappingURL=headless-model.js.map