"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
function _export(target, all) {
    for(var name in all)Object.defineProperty(target, name, {
        enumerable: true,
        get: Object.getOwnPropertyDescriptor(all, name).get
    });
}
_export(exports, {
    get SSCAutocomplete () {
        return SSCAutocomplete;
    },
    get SSCCalculatedQuestion () {
        return SSCCalculatedQuestion;
    },
    get SSCNumber () {
        return SSCNumber;
    },
    get SSCPatientData () {
        return SSCPatientData;
    },
    get SSCResult () {
        return SSCResult;
    },
    get SSCSurveyAnswer () {
        return SSCSurveyAnswer;
    },
    get SSCSurveyLink () {
        return SSCSurveyLink;
    },
    get SSCSurveyResult () {
        return SSCSurveyResult;
    },
    get SSCUserData () {
        return SSCUserData;
    }
});
const _yup = /*#__PURE__*/ _interop_require_wildcard(require("yup"));
const _constants = require("@tamanu/constants");
const _baseSchemas = require("./baseSchemas");
const _jsonString = require("./jsonString");
const _mathjsString = require("./mathjsString");
const _rangeObject = require("./rangeObject");
function _getRequireWildcardCache(nodeInterop) {
    if (typeof WeakMap !== "function") return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache = function(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
        return obj;
    }
    if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
        return {
            default: obj
        };
    }
    var cache = _getRequireWildcardCache(nodeInterop);
    if (cache && cache.has(obj)) {
        return cache.get(obj);
    }
    var newObj = {
        __proto__: null
    };
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for(var key in obj){
        if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc);
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    newObj.default = obj;
    if (cache) {
        cache.set(obj, newObj);
    }
    return newObj;
}
const isIncompatibleCurrentlyAtType = (currentlyAtType, value)=>currentlyAtType === _constants.CURRENTLY_AT_TYPES.VILLAGE && value === 'registrationCurrentlyAtFacility' || currentlyAtType === _constants.CURRENTLY_AT_TYPES.FACILITY && value === 'registrationCurrentlyAtVillage';
const columnReferenceConfig = _baseSchemas.baseConfigShape.shape({
    column: _yup.string().required()
});
const SSCUserData = _baseSchemas.SurveyScreenComponent.shape({
    config: (0, _jsonString.configString)(columnReferenceConfig)
});
const patientDataColumnString = (allowedLocations)=>_yup.string().test('test-valid-patient-data-field', (value, { options, createError, path })=>{
        if (!value) return true;
        if (allowedLocations.includes(value)) return true;
        const { customPatientFieldIds = [] } = options.context;
        if (customPatientFieldIds.includes(value)) return true;
        return createError({
            path,
            message: `${path} must be one of the following values: ${allowedLocations.join(', ')}, or a valid custom patient field ID`
        });
    }).test('test-program-registry-conditions', async (value, { options, createError, path })=>{
        // No need to validate non-program registry fields
        if (!_constants.PROGRAM_REGISTRY_FIELD_LOCATIONS.includes(value)) return true;
        const { models, programId } = options.context;
        const programRegistry = await models.ProgramRegistry.findOne({
            where: {
                programId,
                visibilityStatus: _constants.VISIBILITY_STATUSES.CURRENT
            }
        });
        if (!programRegistry) return createError({
            path,
            message: `${path}=${value} but no program registry configured`
        });
        // Test for incompatible currentlyAtType
        if (isIncompatibleCurrentlyAtType(programRegistry.currentlyAtType, value)) {
            return createError({
                path,
                message: `${path}=${value} but program registry configured for ${programRegistry.currentlyAtType}`
            });
        }
        return true;
    });
const READ_DATA_FIELDS = [
    ...Object.keys(_constants.PATIENT_DATA_FIELD_LOCATIONS),
    ...Object.values(_constants.READONLY_DATA_FIELDS)
];
const WRITE_DATA_FIELDS = Object.keys(_constants.PATIENT_DATA_FIELD_LOCATIONS);
// Note this config needs "source" as a sibling
const whereConfig = ()=>_yup.object().when('source', {
        is: 'ReferenceData',
        then: _yup.object().shape({
            type: _yup.string().required()
        }).required()
    }).default(null).test('only-where-on-referenceData', "where field only used for when source='ReferenceData'", (where, context)=>{
        if (where) {
            return context.options.parent.source === 'ReferenceData';
        }
        return true;
    });
const SSCPatientData = _baseSchemas.SurveyScreenComponent.shape({
    config: (0, _jsonString.configString)(columnReferenceConfig.shape({
        source: _yup.string(),
        where: whereConfig(),
        column: patientDataColumnString(READ_DATA_FIELDS),
        writeToPatient: _yup.object().shape({
            fieldName: patientDataColumnString(WRITE_DATA_FIELDS).required(),
            fieldType: _yup.string().oneOf(_constants.PROGRAM_DATA_ELEMENT_TYPE_VALUES).required()
        }).test('test-isAdditionalData-key-present', 'isAdditionalDataField is deprecated in Tamanu 2.1, it is now just inferred from the fieldName', (writeToPatient)=>!writeToPatient || writeToPatient?.isAdditionalDataField === undefined).noUnknown().default(null)
    }))
});
const sourceReferenceConfig = _baseSchemas.baseConfigShape.shape({
    source: _yup.string().required()
});
const SSCSurveyLink = _baseSchemas.SurveyScreenComponent.shape({
    config: (0, _jsonString.configString)(sourceReferenceConfig)
});
const SSCSurveyResult = _baseSchemas.SurveyScreenComponent.shape({
    config: (0, _jsonString.configString)(sourceReferenceConfig)
});
const SSCSurveyAnswer = _baseSchemas.SurveyScreenComponent.shape({
    config: (0, _jsonString.configString)(sourceReferenceConfig)
});
const SSCAutocomplete = _baseSchemas.SurveyScreenComponent.shape({
    config: (0, _jsonString.configString)(sourceReferenceConfig.shape({
        scope: _yup.string(),
        where: whereConfig()
    }))
});
const numberConfig = _baseSchemas.baseConfigShape.shape({
    unit: _yup.string(),
    rounding: _yup.number()
});
const numberValidationCriteria = _baseSchemas.baseValidationShape.shape({
    min: _yup.number(),
    max: _yup.number(),
    normalRange: _yup.lazy((value)=>Array.isArray(value) ? _rangeObject.rangeArraySchema : _rangeObject.rangeObjectSchema)
});
const SSCNumber = _baseSchemas.SurveyScreenComponent.shape({
    config: (0, _jsonString.configString)(numberConfig),
    validationCriteria: (0, _jsonString.validationString)(numberValidationCriteria)
});
const SSCCalculatedQuestion = _baseSchemas.SurveyScreenComponent.shape({
    config: (0, _jsonString.configString)(numberConfig),
    validationCriteria: (0, _jsonString.validationString)(numberValidationCriteria),
    calculation: (0, _mathjsString.mathjsString)().required()
});
const SSCResult = _baseSchemas.SurveyScreenComponent.shape({
    config: (0, _jsonString.configString)(numberConfig),
    validationCriteria: (0, _jsonString.validationString)(numberValidationCriteria),
    calculation: (0, _mathjsString.mathjsString)()
});

//# sourceMappingURL=questionSchemas.js.map