"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createSequentialEmbeddedSignatureRequest = 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.createSequentialEmbeddedSignatureRequest = {
    key: 'createSequentialEmbeddedSignatureRequest',
    title: 'Create sequential embedded signature request',
    description: 'Create an embedded signature request with sequential signing. Adds both Recipient 1 (routing order 1) and Recipient 2 (routing order 2) to the envelope, but only generates the Recipient 1 sign URL. Use "Generate sign URL for existing envelope" action after Recipient 1 signs to get the Recipient 2 URL.',
    category: extensions_core_2.Category.DOCUMENT_MANAGEMENT,
    fields: config_1.fields,
    dataPoints: config_1.dataPoints,
    previewable: false,
    onEvent: async ({ payload, onComplete, onError }) => {
        var _a;
        const { patient: { id: patientId }, pathway: { id: pathwayId }, activity: { id: activityId, sessionId }, } = payload;
        const { settings: { accountId, baseApiUrl, returnUrlTemplate, integrationKey, rsaKey, userId, }, fields: { templateId, subject, message, patientSignerRole, patientSignerName, patientSignerEmail, providerSignerRole, providerSignerName, providerSignerEmail, providerClientUserId, }, } = (0, extensions_core_1.validate)({
            schema: zod_1.z.object({
                settings: settings_1.SettingsValidationSchema,
                fields: config_1.FieldsValidationSchema,
            }),
            payload,
        });
        const client = await (0, createClient_1.createApiClient)({
            integrationKey,
            userId,
            rsaKey,
            baseUrl: baseApiUrl,
        });
        const recipient1Signer = docusign_esign_1.default.TemplateRole.constructFromObject({
            email: patientSignerEmail,
            name: patientSignerName,
            roleName: patientSignerRole,
            clientUserId: patientId,
            routingOrder: '1',
        });
        const recipient2Signer = docusign_esign_1.default.TemplateRole.constructFromObject({
            email: providerSignerEmail,
            name: providerSignerName,
            roleName: providerSignerRole,
            clientUserId: providerClientUserId,
            routingOrder: '2',
        });
        const envelope = docusign_esign_1.default.EnvelopeDefinition.constructFromObject({
            status: 'sent',
            templateId,
            templateRoles: [recipient1Signer, recipient2Signer],
            emailSubject: subject,
            emailBlurb: message,
        });
        const envelopesApi = new docusign_esign_1.default.EnvelopesApi(client);
        try {
            const envelopeResult = await envelopesApi.createEnvelope(accountId, {
                envelopeDefinition: envelope,
            });
            const recipient1ViewRequest = docusign_esign_1.default.RecipientViewRequest.constructFromObject({
                authenticationMethod: 'none',
                email: patientSignerEmail,
                userName: patientSignerName,
                clientUserId: patientId,
                returnUrl: (0, utils_1.replaceStringVariables)(returnUrlTemplate, {
                    sessionId: sessionId !== null && sessionId !== void 0 ? sessionId : '',
                    stakeholderId: patientId,
                    pathwayId,
                    activityId,
                }),
            });
            const recipient1ViewResult = await envelopesApi.createRecipientView(accountId, (_a = envelopeResult === null || envelopeResult === void 0 ? void 0 : envelopeResult.envelopeId) !== null && _a !== void 0 ? _a : '', {
                recipientViewRequest: recipient1ViewRequest,
            });
            await onComplete({
                data_points: {
                    envelopeId: envelopeResult === null || envelopeResult === void 0 ? void 0 : envelopeResult.envelopeId,
                    recipient1SignUrl: recipient1ViewResult === null || recipient1ViewResult === void 0 ? void 0 : recipient1ViewResult.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=createSequentialEmbeddedSignatureRequest.js.map