"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "getProgramSurveysWithFormVisibility", {
    enumerable: true,
    get: function() {
        return getProgramSurveysWithFormVisibility;
    }
});
const _sequelize = require("sequelize");
const _criteria = require("@tamanu/utils/criteria");
const _getLastSurveyAnswerValuesByQuestionCodes = require("./getLastSurveyAnswerValuesByQuestionCodes");
async function getProgramSurveysWithFormVisibility(models, surveys, patientId) {
    const data = surveys.map((s)=>({
            ...s.forResponse(),
            passesFormVisibility: true
        }));
    if (!patientId) {
        return data;
    }
    const questionCodes = [
        ...new Set(surveys.flatMap((s)=>(0, _criteria.getQuestionCodesFromFormVisibilityCriteria)(s.visibilityCriteria ?? '')))
    ].filter(Boolean);
    if (questionCodes.length === 0) {
        return data;
    }
    const valuesByCode = await (0, _getLastSurveyAnswerValuesByQuestionCodes.getLastSurveyAnswerValuesByQuestionCodes)(models, patientId, questionCodes);
    const dataElements = await models.ProgramDataElement.findAll({
        where: {
            code: {
                [_sequelize.Op.in]: questionCodes
            }
        },
        attributes: [
            'code',
            'type'
        ]
    });
    const typesByCode = dataElements.reduce((acc, el)=>{
        acc[el.code] = el.type;
        return acc;
    }, {});
    const surveyById = new Map(surveys.map((s)=>[
            s.id,
            s
        ]));
    for (const item of data){
        const criteria = surveyById.get(item.id)?.visibilityCriteria;
        if (criteria?.trim()) {
            item.passesFormVisibility = (0, _criteria.checkFormVisibilityCriteria)(criteria, valuesByCode, typesByCode);
        }
    }
    return data;
}

//# sourceMappingURL=getProgramSurveysWithFormVisibility.js.map