"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.sendSms = void 0;
const extensions_core_1 = require("@awell-health/extensions-core");
const lodash_1 = require("lodash");
const validatePayloadAndCreateSdk_1 = require("../../lib/validatePayloadAndCreateSdk");
const config_1 = require("./config");
const schema_1 = require("../../api/schema");
const addEventLog_1 = require("../../../../src/lib/awell/addEventLog");
exports.sendSms = {
    key: 'sendSms',
    category: extensions_core_1.Category.COMMUNICATION,
    title: 'Send SMS',
    description: 'Send an SMS message immediately. The agent message is optional when a pathway drives the conversation.',
    fields: config_1.fields,
    previewable: true,
    dataPoints: config_1.dataPoints,
    supports_automated_retries: true,
    onEvent: async ({ payload, onComplete, onError, helpers }) => {
        var _a;
        helpers.log({ fields: payload.fields }, 'Processing sendSms');
        try {
            const { fields, blandSdk } = await (0, validatePayloadAndCreateSdk_1.validatePayloadAndCreateSdk)({
                fieldsSchema: config_1.FieldsValidationSchema,
                payload,
            });
            const getWebhookUrl = () => {
                var _a;
                if ((0, lodash_1.isEmpty)(fields.webhook))
                    return undefined;
                const separator = ((_a = fields.webhook) === null || _a === void 0 ? void 0 : _a.includes('?')) === true ? '&' : '?';
                return `${fields.webhook}${separator}activity_id=${payload.activity.id}`;
            };
            const sendSmsInput = schema_1.SendSmsInputSchema.parse({
                user_number: fields.userNumber,
                agent_number: fields.agentNumber,
                agent_message: (0, lodash_1.isEmpty)(fields.agentMessage)
                    ? undefined
                    : fields.agentMessage,
                pathway_id: (0, lodash_1.isEmpty)(fields.pathwayId) ? undefined : fields.pathwayId,
                new_conversation: fields.newConversation,
                webhook: getWebhookUrl(),
                time_out: fields.timeOut,
                timeout_message: (0, lodash_1.isEmpty)(fields.timeoutMessage)
                    ? undefined
                    : fields.timeoutMessage,
                warning_time: fields.warningTime,
                warning_message: (0, lodash_1.isEmpty)(fields.warningMessage)
                    ? undefined
                    : fields.warningMessage,
                request_data: (0, lodash_1.isEmpty)(fields.requestData)
                    ? undefined
                    : fields.requestData,
                metadata: {
                    ...fields.metadata,
                    awell_patient_id: payload.patient.id,
                    awell_care_flow_definition_id: payload.pathway.definition_id,
                    awell_care_flow_id: payload.pathway.id,
                    awell_activity_id: payload.activity.id,
                },
            });
            try {
                helpers.log({ sendSmsInput }, 'Sending SMS via Bland');
            }
            catch (err) {
                console.error('unable to use new helpers.log');
                console.error(JSON.stringify(err));
            }
            const { data } = await blandSdk.sendSms(sendSmsInput);
            const conversationId = (_a = data === null || data === void 0 ? void 0 : data.data) === null || _a === void 0 ? void 0 : _a.conversation_id;
            await onComplete({
                data_points: {
                    conversationId: (0, lodash_1.isNil)(conversationId) ? undefined : conversationId,
                    smsResponse: (0, lodash_1.isNil)(data) ? undefined : JSON.stringify(data),
                },
                events: [
                    (0, addEventLog_1.addActivityEventLog)({
                        message: `SMS request sent to Bland.\nConversation ID: ${conversationId !== null && conversationId !== void 0 ? conversationId : 'n/a'}`,
                    }),
                ],
            });
        }
        catch (err) {
            helpers.log({ err }, 'error', err);
            const error = err;
            await onError({
                events: [
                    {
                        date: new Date().toISOString(),
                        text: { en: error.message },
                        error: {
                            category: 'SERVER_ERROR',
                            message: error.message,
                        },
                    },
                ],
            });
        }
    },
};
//# sourceMappingURL=sendSms.js.map