"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.patientCreatedOrUpdated = void 0;
const settings_1 = require("../settings");
const lodash_1 = require("lodash");
const dataPoints = {
    patientId: {
        key: 'patientId',
        valueType: 'number',
    },
    patient: {
        key: 'patient',
        valueType: 'json',
    },
};
exports.patientCreatedOrUpdated = {
    key: 'patientCreatedOrUpdated',
    dataPoints,
    onEvent: async ({ payload: { payload, settings, endpoint }, onSuccess, onError, helpers: { rateLimiter }, }) => {
        var _a, _b;
        const { data, resource, action } = payload;
        const { id: patientId } = data;
        // skip non 'saved' actions for that webhook
        if (action !== 'saved') {
            return;
        }
        // rate limiting
        const { success, data: durationString } = settings_1.rateLimitDurationSchema.safeParse(settings.rateLimitDuration);
        if (success && !(0, lodash_1.isNil)(durationString)) {
            const duration = (0, settings_1.transformRateLimitDuration)(durationString);
            const limiterName = `elation-patient-${(_a = endpoint === null || endpoint === void 0 ? void 0 : endpoint.id) !== null && _a !== void 0 ? _a : 'global'}`;
            const limiter = rateLimiter(limiterName, {
                requests: 1,
                duration,
            });
            const key = patientId.toString();
            const { success } = await limiter.limit(key);
            if (!success) {
                await onError({
                    response: {
                        statusCode: 200,
                        message: `Rate limit exceeded on limiter ${limiterName} for key ${key}. 200 OK response sent to Elation to prevent further requests for patient ${patientId} on endpoint ${(_b = endpoint === null || endpoint === void 0 ? void 0 : endpoint.url) !== null && _b !== void 0 ? _b : 'global'}.`,
                    },
                });
                return;
            }
        }
        if (resource !== 'patients') {
            await onError({
                response: {
                    statusCode: 400,
                    message: 'resource must be patients',
                },
            });
        }
        else {
            await onSuccess({
                data_points: {
                    patientId: String(data.id),
                    patient: JSON.stringify(data),
                },
                // Review the system used for elation identifiers
                patient_identifier: {
                    system: 'https://www.elationhealth.com/',
                    value: String(data.id),
                },
            });
        }
    },
};
//# sourceMappingURL=patientCreatedOrUpdated.js.map