"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.formAnswerGroupLocked = void 0;
const lodash_1 = require("lodash");
const types_1 = require("../lib/types");
const settings_1 = require("../settings");
const errors_1 = require("../lib/sdk/graphql-codegen/errors");
const createSdk_1 = require("../lib/sdk/graphql-codegen/createSdk");
const helpers_1 = require("../lib/helpers");
const processFormAnswers_1 = require("../lib/helpers/processFormAnswers");
const dataPoints = {
    lockedFormAnswerGroupId: {
        key: 'lockedFormAnswerGroupId',
        valueType: 'string',
    },
    lockedFormAnswerGroup: {
        key: 'lockedFormAnswerGroup',
        valueType: 'json',
    },
};
exports.formAnswerGroupLocked = {
    key: 'formAnswerGroupLocked',
    dataPoints,
    onWebhookReceived: async ({ payload, settings }, onSuccess, onError) => {
        var _a, _b;
        try {
            const { sdk } = await (0, createSdk_1.createSdk)({ settings });
            const formAnswerMaxSizeKB = settings_1.SettingsValidationSchema.parse(settings).formAnswerMaxSizeKB;
            const validatedPayload = helpers_1.webhookPayloadSchema.parse(payload);
            const lockedFormAnswerGroupId = validatedPayload.resource_id.toString();
            const response = await sdk.getFormAnswerGroup({
                id: lockedFormAnswerGroupId,
            });
            const rawFormAnswerGroup = (_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.formAnswerGroup;
            if (!rawFormAnswerGroup) {
                throw new Error('Form answer group not found');
            }
            // Process form answers to replace large ones with error messages
            const processedFormAnswerGroup = (0, processFormAnswers_1.processFormAnswersForSize)(rawFormAnswerGroup, formAnswerMaxSizeKB);
            const healthiePatientId = (_b = processedFormAnswerGroup.user) === null || _b === void 0 ? void 0 : _b.id;
            await onSuccess({
                data_points: {
                    lockedFormAnswerGroupId,
                    lockedFormAnswerGroup: JSON.stringify(processedFormAnswerGroup),
                },
                ...(!(0, lodash_1.isNil)(healthiePatientId) && {
                    patient_identifier: {
                        system: types_1.HEALTHIE_IDENTIFIER,
                        value: healthiePatientId,
                    },
                }),
            });
        }
        catch (error) {
            await onError((0, errors_1.formatError)(error));
        }
    },
};
//# sourceMappingURL=formAnswerGroupLocked.js.map