"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createQuestionnaireResponses = void 0;
const extensions_core_1 = require("@awell-health/extensions-core");
const extensions_core_2 = require("@awell-health/extensions-core");
const config_1 = require("./config");
const utils_1 = require("../../utils");
const zod_1 = require("zod");
const client_1 = require("../../client");
const validation_1 = require("../../validation");
exports.createQuestionnaireResponses = {
    key: 'createQuestionnaireResponses',
    category: extensions_core_2.Category.EHR_INTEGRATIONS,
    title: 'Create a response to a questionnaire',
    description: 'Create a response to a questionnaire',
    fields: config_1.fields,
    dataPoints: config_1.dataPoints,
    previewable: true,
    onActivityCreated: async (payload, onComplete, onError) => {
        try {
            (0, extensions_core_1.validate)({
                schema: zod_1.z.object({
                    fields: config_1.fieldsValidationSchema,
                }),
                payload,
            });
            const { questionnaireId, subjectId, authorId, authored, item } = payload.fields;
            const questionnaireResponses = validation_1.creatingQuestionnaireResponsesSchema.parse(createPayload(questionnaireId, subjectId, authored, authorId, JSON.parse(item)));
            const api = (0, client_1.makeAPIClient)(payload.settings);
            const questionnaireResponseId = await api.createQuestionnaireResponses(questionnaireResponses);
            await onComplete({
                data_points: {
                    questionnaireResponseId,
                },
            });
        }
        catch (error) {
            let parsedError;
            if ((0, utils_1.isZodError)(error)) {
                parsedError = (0, utils_1.parseZodError)(error);
            }
            else if ((0, utils_1.isAxiosError)(error)) {
                parsedError = (0, utils_1.parseAxiosError)(error);
            }
            else {
                parsedError = (0, utils_1.parseUnknowError)(error);
            }
            await onError({
                events: [parsedError],
            });
        }
    },
};
const createPayload = (questionnaireId, subjectId, authored, authorId, item) => {
    const payload = {
        resourceType: 'QuestionnaireResponse',
        questionnaire: questionnaireId !== undefined
            ? `Questionnaire/${questionnaireId}`
            : undefined,
        subject: subjectId !== undefined
            ? {
                reference: `Patient/${subjectId}`,
            }
            : undefined,
        item,
        authored: authored !== null && authored !== void 0 ? authored : new Date().toISOString(),
        author: authorId !== undefined
            ? {
                reference: `Practitioner/${authorId}`,
            }
            : undefined,
    };
    return payload;
};
//# sourceMappingURL=createQuestionnaireResponses.js.map