"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.appointmentCreatedOrUpdated = void 0;
const constants_1 = require("../constants");
const settings_1 = require("../settings");
const lodash_1 = require("lodash");
const dataPoints = {
    appointmentId: {
        key: 'appointmentId',
        valueType: 'number',
    },
    appointment: {
        key: 'appointment',
        valueType: 'json',
    },
};
exports.appointmentCreatedOrUpdated = {
    key: 'appointmentCreatedOrUpdated',
    dataPoints,
    onEvent: async ({ payload: { payload, settings, endpoint }, onSuccess, onError, helpers: { rateLimiter }, }) => {
        var _a, _b;
        const { action, resource, data } = payload;
        const { id: appointmentId, patient: 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-appointment-${(_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 = appointmentId.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 appointment ${appointmentId} on endpoint ${(_b = endpoint === null || endpoint === void 0 ? void 0 : endpoint.url) !== null && _b !== void 0 ? _b : 'global'}.`,
                    },
                });
                return;
            }
        }
        if (resource !== 'appointments') {
            await onError({
                response: {
                    statusCode: 400,
                    message: 'resource must be apppointments',
                },
            });
        }
        else {
            await onSuccess({
                data_points: {
                    appointmentId: String(appointmentId),
                    appointment: JSON.stringify(data),
                },
                patient_identifier: {
                    system: constants_1.ELATION_SYSTEM,
                    value: String(patientId),
                },
            });
        }
    },
};
//# sourceMappingURL=appointmentCreatedOrUpdated.js.map