"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "translationRouter", {
    enumerable: true,
    get: function() {
        return translationRouter;
    }
});
const _express = /*#__PURE__*/ _interop_require_default(require("express"));
const _expressasynchandler = /*#__PURE__*/ _interop_require_default(require("express-async-handler"));
const _lodash = require("lodash");
const _queryTranslatedStringsByLanguage = require("@tamanu/shared/utils/translation/queryTranslatedStringsByLanguage");
const _constants = require("@tamanu/constants");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
const translationRouter = _express.default.Router();
// Bump default json limit as some deployments have a large number of translations
translationRouter.get('/', (0, _expressasynchandler.default)(async (req, res)=>{
    const { store } = req;
    req.flagPermissionChecked();
    const languageNames = await store.models.TranslatedString.findAll({
        attributes: [
            'language',
            'text'
        ],
        where: {
            stringId: _constants.LANGUAGE_NAME_STRING_ID
        }
    });
    const translations = await (0, _queryTranslatedStringsByLanguage.queryTranslatedStringsByLanguage)(store);
    res.send({
        translations,
        languageNames: (languageNames || []).reduce((acc, { language, text })=>({
                ...acc,
                [language]: text
            }), {})
    });
}));
translationRouter.put('/', (0, _expressasynchandler.default)(async (req, res)=>{
    const { store, body } = req;
    const { models: { TranslatedString }, sequelize } = store;
    req.checkPermission('write', 'Translation');
    const upsertTranslation = async ({ stringId, language, text })=>{
        if (language === _constants.DEFAULT_LANGUAGE_CODE) return []; // Ignore default translations
        const updateAndRestore = async (existing, text)=>{
            let restored = false;
            if (existing.deletedAt) {
                await existing.restore();
                restored = true;
            }
            return [
                await existing.update({
                    text
                }),
                restored
            ];
        };
        // Postgres doesn't return any information about whether an upserted row was created or updated
        // so we have to check for an existing row first and match the return style of upsert i.e [record, isCreate].
        const existing = await TranslatedString.findOne({
            where: {
                stringId,
                language
            },
            paranoid: false
        });
        if ((0, _lodash.isEmpty)(text) && !existing) return [];
        if ((0, _lodash.isEmpty)(text) && existing) return [
            await existing.destroy(),
            false
        ];
        if (existing?.text === text && !existing.deletedAt) return [];
        if (existing) return await updateAndRestore(existing, text);
        return [
            await TranslatedString.create({
                stringId,
                language,
                text
            }),
            true
        ];
    };
    const results = await sequelize.transaction(async ()=>{
        // Convert FE representation of translation data (grouped by stringId with keys for each languages text)
        // to upsertable entries.
        return Promise.all(Object.entries(body).flatMap(([stringId, languages])=>Object.entries(languages).map(([language, text])=>upsertTranslation({
                    stringId,
                    language,
                    text
                }))));
    });
    const newlyCreated = results.filter((result)=>result[1]).map((result)=>result[0].get({
            plain: true
        }));
    if (newlyCreated.length) {
        res.status(201).send({
            data: newlyCreated
        });
        return;
    }
    res.send({
        ok: 'ok'
    });
}));

//# sourceMappingURL=translation.js.map