"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.sendSms = void 0;
const zod_1 = require("zod");
const twilio_1 = __importDefault(require("../../../common/sdk/twilio"));
const extensions_core_1 = require("@awell-health/extensions-core");
const settings_1 = require("../../../settings");
const config_1 = require("./config");
const lodash_1 = require("lodash");
const lib_1 = require("../../../lib");
const errors_1 = require("../../../lib/errors");
exports.sendSms = {
    key: 'sendSms',
    title: 'Send SMS (with from number)',
    description: 'Send a text message from a given telephone number to a recipient of your choice.',
    category: extensions_core_1.Category.COMMUNICATION,
    fields: config_1.fields,
    dataPoints: config_1.dataPoints,
    previewable: true,
    onEvent: async ({ payload, onComplete, onError, helpers }) => {
        helpers.log({ fields: payload.fields }, 'Processing sendSms');
        try {
            const { settings: { accountSid, authToken, fromNumber: defaultFromNumber, addOptOutLanguage, optOutLanguage, language, }, fields: { recipient, message, from }, } = (0, extensions_core_1.validate)({
                schema: zod_1.z
                    .object({
                    settings: settings_1.SettingsValidationSchema,
                    fields: config_1.FieldsValidationSchema,
                })
                    .superRefine((value, ctx) => {
                    // if both `from` values missing - throw error
                    if ((0, lodash_1.isNil)(value.settings.fromNumber) && (0, lodash_1.isNil)(value.fields.from)) {
                        ctx.addIssue({
                            code: zod_1.z.ZodIssueCode.custom,
                            fatal: true,
                            message: '"From" number is missing in both settings and in the action field.',
                        });
                    }
                }),
                payload,
            });
            const client = (0, twilio_1.default)(accountSid, authToken, {
                region: 'IE1',
                accountSid,
            });
            const { sid } = await client.messages.create({
                body: addOptOutLanguage
                    ? (0, lib_1.appendOptOutLanguage)(message, optOutLanguage, language)
                    : message,
                from: from !== null && from !== void 0 ? from : defaultFromNumber,
                to: recipient,
            });
            const messageSidLog = `Message SID: ${sid}`;
            await onComplete({
                data_points: {
                    messageSid: sid,
                },
                events: [
                    {
                        date: new Date().toISOString(),
                        text: {
                            en: messageSidLog,
                        },
                    },
                ],
            });
        }
        catch (error) {
            helpers.log({ error }, 'error', error);
            if ((0, errors_1.isTwilioErrorResponse)(error)) {
                await onError({
                    events: [(0, errors_1.parseTwilioError)(error)],
                });
            }
            else {
                // we handle ZodError and unknown errors in extension-server directly
                throw error;
            }
        }
    },
};
//# sourceMappingURL=sendSms.js.map