"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateSignUrlForExistingEnvelope = void 0;
const extensions_core_1 = require("@awell-health/extensions-core");
const docusign_esign_1 = __importDefault(require("docusign-esign"));
const extensions_core_2 = require("@awell-health/extensions-core");
const zod_1 = require("zod");
const config_1 = require("./config");
const settings_1 = require("../../settings");
const createClient_1 = require("../createEmbeddedSignatureRequestWithTemplate/config/createClient");
const types_1 = require("../createEmbeddedSignatureRequestWithTemplate/config/types");
const utils_1 = require("../createEmbeddedSignatureRequestWithTemplate/config/utils");
exports.generateSignUrlForExistingEnvelope = {
    key: 'generateSignUrlForExistingEnvelope',
    title: 'Generate sign URL for existing envelope',
    description: 'Generate a signing URL for a recipient in an existing DocuSign envelope. Useful for sequential signing workflows where multiple people sign the same document in order.',
    category: extensions_core_2.Category.DOCUMENT_MANAGEMENT,
    fields: config_1.fields,
    dataPoints: config_1.dataPoints,
    previewable: true,
    onEvent: async ({ payload, onComplete, onError }) => {
        const { patient: { id: patientId }, pathway: { id: pathwayId }, activity: { id: activityId, sessionId }, } = payload;
        const { settings: { accountId, baseApiUrl, returnUrlTemplate, integrationKey, rsaKey, userId, }, fields: { envelopeId, signerName, signerEmail, clientUserId }, } = (0, extensions_core_1.validate)({
            schema: zod_1.z.object({
                settings: settings_1.SettingsValidationSchema,
                fields: config_1.FieldsValidationSchema,
            }),
            payload,
        });
        try {
            const client = await (0, createClient_1.createApiClient)({
                integrationKey,
                userId,
                rsaKey,
                baseUrl: baseApiUrl,
            });
            const envelopesApi = new docusign_esign_1.default.EnvelopesApi(client);
            const viewRequest = docusign_esign_1.default.RecipientViewRequest.constructFromObject({
                authenticationMethod: 'none',
                email: signerEmail,
                userName: signerName,
                clientUserId,
                returnUrl: (0, utils_1.replaceStringVariables)(returnUrlTemplate, {
                    sessionId: sessionId !== null && sessionId !== void 0 ? sessionId : '',
                    stakeholderId: clientUserId,
                    pathwayId,
                    activityId,
                }),
            });
            const viewResult = await envelopesApi.createRecipientView(accountId, envelopeId, {
                recipientViewRequest: viewRequest,
            });
            await onComplete({
                data_points: {
                    signUrl: viewResult === null || viewResult === void 0 ? void 0 : viewResult.url,
                },
            });
        }
        catch (err) {
            if ((0, types_1.instanceOfDocuSignError)(err)) {
                await onError({
                    events: [
                        {
                            date: new Date().toISOString(),
                            text: {
                                en: `DocuSign reported an error: ${err.response.text}`,
                            },
                            error: {
                                category: 'BAD_REQUEST',
                                message: `DocuSign error (${String(err.response.status)}): ${err.response.text}`,
                            },
                        },
                    ],
                });
                return;
            }
            throw err;
        }
    },
};
//# sourceMappingURL=generateSignUrlForExistingEnvelope.js.map