"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createEmbeddedSignatureRequestWithTemplate = void 0;
const docusign_esign_1 = __importDefault(require("docusign-esign"));
const extensions_core_1 = require("@awell-health/extensions-core");
const zod_validation_error_1 = require("zod-validation-error");
const config_1 = require("./config");
const settings_1 = require("../../settings");
const zod_1 = require("zod");
const createClient_1 = require("./config/createClient");
const types_1 = require("./config/types");
const utils_1 = require("./config/utils");
exports.createEmbeddedSignatureRequestWithTemplate = {
    key: 'createEmbeddedSignatureRequestWithTemplate',
    title: 'Create embedded signature request with template',
    description: 'Let a stakeholder sign a request within Awell based off a template. The care flow will not progress until the request is signed.',
    category: extensions_core_1.Category.DOCUMENT_MANAGEMENT,
    fields: config_1.fields,
    dataPoints: config_1.dataPoints,
    previewable: true,
    onActivityCreated: async (payload, onComplete, onError) => {
        var _a;
        try {
            const { patient: { id: patientId }, pathway: { id: pathwayId }, activity: { id: activityId, sessionId }, } = payload;
            const { signerRole, signerName, signerEmailAddress, templateId, subject, message, } = (0, config_1.validateActionFields)(payload.fields);
            const { accountId, baseApiUrl, returnUrlTemplate, integrationKey, rsaKey, userId, } = (0, settings_1.validateSettings)(payload.settings);
            const client = await (0, createClient_1.createApiClient)({
                integrationKey,
                userId,
                rsaKey,
                baseUrl: baseApiUrl,
            });
            const signer = docusign_esign_1.default.TemplateRole.constructFromObject({
                email: signerEmailAddress,
                name: signerName,
                roleName: signerRole,
                clientUserId: patientId,
            });
            const envelope = docusign_esign_1.default.EnvelopeDefinition.constructFromObject({
                status: 'sent',
                templateId,
                templateRoles: [signer],
                emailSubject: subject,
                emailBlurb: message,
            });
            const envelopesApi = new docusign_esign_1.default.EnvelopesApi(client);
            const envelopeResult = await envelopesApi.createEnvelope(accountId, {
                envelopeDefinition: envelope,
            });
            const viewRequest = docusign_esign_1.default.RecipientViewRequest.constructFromObject({
                authenticationMethod: 'none',
                email: signerEmailAddress,
                userName: signerName,
                clientUserId: patientId,
                returnUrl: (0, utils_1.replaceStringVariables)(returnUrlTemplate, {
                    sessionId: sessionId !== null && sessionId !== void 0 ? sessionId : '',
                    stakeholderId: patientId,
                    pathwayId,
                    activityId,
                }),
            });
            const viewRequestResult = await envelopesApi.createRecipientView(accountId, (_a = envelopeResult === null || envelopeResult === void 0 ? void 0 : envelopeResult.envelopeId) !== null && _a !== void 0 ? _a : '', {
                recipientViewRequest: viewRequest,
            });
            await onComplete({
                data_points: {
                    envelopeId: envelopeResult === null || envelopeResult === void 0 ? void 0 : envelopeResult.envelopeId,
                    signUrl: viewRequestResult === null || viewRequestResult === void 0 ? void 0 : viewRequestResult.url,
                },
            });
        }
        catch (err) {
            if (err instanceof zod_1.ZodError) {
                const error = (0, zod_validation_error_1.fromZodError)(err);
                await onError({
                    events: [
                        {
                            date: new Date().toISOString(),
                            text: { en: error.name },
                            error: {
                                category: 'WRONG_INPUT',
                                message: `${error.message}`,
                            },
                        },
                    ],
                });
                return;
            }
            if ((0, types_1.instanceOfDocuSignError)(err)) {
                await onError({
                    events: [
                        {
                            date: new Date().toISOString(),
                            text: {
                                en: err.response.text,
                            },
                            error: {
                                category: 'SERVER_ERROR',
                                message: `${String(err.response.status)}: ${err.response.text}`,
                            },
                        },
                    ],
                });
                return;
            }
            const error = err;
            await onError({
                events: [
                    {
                        date: new Date().toISOString(),
                        text: { en: 'Something went wrong while orchestration the action' },
                        error: {
                            category: 'SERVER_ERROR',
                            message: error.message,
                        },
                    },
                ],
            });
        }
    },
};
//# sourceMappingURL=createEmbeddedSignatureRequestWithTemplate.js.map