"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.closeCareGap = void 0;
const extensions_core_1 = require("@awell-health/extensions-core");
const zod_1 = require("zod");
const client_1 = require("../../client");
const settings_1 = require("../../settings");
const config_1 = require("./config");
exports.closeCareGap = {
    key: 'closeCareGap',
    category: extensions_core_1.Category.EHR_INTEGRATIONS,
    title: 'Close care gap',
    description: 'Close a care gap in Elation.',
    fields: config_1.fields,
    previewable: true,
    dataPoints: config_1.dataPoints,
    onEvent: async ({ payload, onComplete, onError, helpers }) => {
        try {
            const { fields: { quality_program, caregap_id }, settings, } = (0, extensions_core_1.validate)({
                schema: zod_1.z.object({
                    fields: config_1.FieldsValidationSchema,
                    settings: settings_1.SettingsValidationSchema,
                }),
                payload,
            });
            // The care gap API uses a different base URL than the rest of the Elation API, see https://docs.elationhealth.com/reference/caregaps_post_caregaps_api__quality_program__caregap__post-1
            const caregapBaseUrl = settings.base_url.replace(/(.+\.)?elationemr\.com\/api\/2\.0\/?/, 'caregaps.$1elationemr.com/caregaps/api/');
            const api = (0, client_1.makeAPIClient)({
                ...payload.settings,
                baseUrl: caregapBaseUrl,
            });
            const closeCareGapRequest = {
                quality_program,
                caregap_id,
                status: 'closed',
            };
            helpers.log({ closeCareGapRequest }, 'Closing Elation care gap');
            await api.closeCareGap(closeCareGapRequest);
            await onComplete();
        }
        catch (err) {
            const message = err.message;
            helpers.log({ err }, 'error', err);
            await onError({
                events: [
                    {
                        date: new Date().toISOString(),
                        text: { en: message },
                        error: {
                            category: 'SERVER_ERROR',
                            message,
                        },
                    },
                ],
            });
        }
    },
};
//# sourceMappingURL=closeCareGap.js.map