"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSetPasswordLink = void 0;
const extensions_core_1 = require("@awell-health/extensions-core");
const config_1 = require("./config");
const validatePayloadAndCreateSdk_1 = require("../../lib/sdk/validatePayloadAndCreateSdk");
const lodash_1 = require("lodash");
exports.getSetPasswordLink = {
    key: 'getSetPasswordLink',
    category: extensions_core_1.Category.EHR_INTEGRATIONS,
    title: 'Get set password link',
    description: 'Get the set password link for a patient',
    fields: config_1.fields,
    previewable: false,
    dataPoints: config_1.dataPoints,
    onActivityCreated: async (payload, onComplete, onError) => {
        var _a, _b;
        const MAX_RETRIES = 3;
        const BASE_DELAY_MS = process.env.NODE_ENV === 'test' ? 10 : 1000;
        const { fields, healthieSdk } = await (0, validatePayloadAndCreateSdk_1.validatePayloadAndCreateSdk)({
            fieldsSchema: config_1.FieldsValidationSchema,
            payload,
        });
        let setPasswordLink;
        /**
         * We need to retry the API call because:
         * - The setPasswordLink field is not immediately available after creating a new user.
         * - The API response is inconsistent
         */
        for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
            const res = await healthieSdk.client.query({
                user: {
                    __args: {
                        id: fields.healthiePatientId,
                    },
                    set_password_link: true,
                },
            });
            if (!(0, lodash_1.isNil)((_a = res.user) === null || _a === void 0 ? void 0 : _a.set_password_link)) {
                setPasswordLink = String((_b = res.user) === null || _b === void 0 ? void 0 : _b.set_password_link);
                break;
            }
            // Exponential backoff delay calculation
            const delay = BASE_DELAY_MS * Math.pow(2, attempt);
            await new Promise((resolve) => setTimeout(resolve, delay));
        }
        await onComplete({
            data_points: {
                setPasswordLink: setPasswordLink === undefined || setPasswordLink === null
                    ? undefined
                    : String(setPasswordLink),
            },
        });
    },
};
//# sourceMappingURL=getSetPasswordLink.js.map