"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "complexChartInstancePutHandler", {
    enumerable: true,
    get: function() {
        return complexChartInstancePutHandler;
    }
});
const _ability = require("@casl/ability");
const _expressasynchandler = /*#__PURE__*/ _interop_require_default(require("express-async-handler"));
const _constants = require("@tamanu/constants");
const _errors = require("@tamanu/errors");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
const complexChartInstancePutHandler = (0, _expressasynchandler.default)(async (req, res)=>{
    const { models, body, params, db } = req;
    const responseRecord = await models.SurveyResponse.findByPk(params.id);
    if (!responseRecord) {
        throw new _errors.NotFoundError('Response record not found');
    }
    req.checkPermission('write', (0, _ability.subject)('Charting', {
        id: responseRecord.surveyId
    }));
    const survey = await responseRecord.getSurvey();
    if (survey.surveyType !== _constants.SURVEY_TYPES.COMPLEX_CHART_CORE) {
        throw new _errors.InvalidOperationError('Cannot edit survey responses');
    }
    const components = await models.SurveyScreenComponent.getComponentsForSurvey(survey.id);
    const responseAnswers = await models.SurveyResponseAnswer.findAll({
        where: {
            responseId: params.id
        }
    });
    await db.transaction(async ()=>{
        for (const [dataElementId, value] of Object.entries(body.answers)){
            if (!components.some((c)=>c.dataElementId === dataElementId)) {
                throw new _errors.InvalidOperationError('Some components are missing from the survey');
            }
            // Ignore null values
            if (value === null) {
                continue;
            }
            const existingAnswer = responseAnswers.find((a)=>a.dataElementId === dataElementId);
            if (existingAnswer) {
                await existingAnswer.update({
                    body: value
                });
            } else {
                await models.SurveyResponseAnswer.create({
                    dataElementId,
                    body: value,
                    responseId: params.id
                });
            }
        }
    });
    res.send(responseRecord);
});

//# sourceMappingURL=complexChartInstance.js.map