"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.sendSms = void 0;
const zod_1 = require("zod");
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 error_1 = require("../../client/error");
const client_1 = require("../../client");
exports.sendSms = {
    key: 'sendSms',
    title: 'Send SMS',
    description: 'Sends SMS using Infobip',
    category: extensions_core_1.Category.COMMUNICATION,
    fields: config_1.fields,
    previewable: false,
    onActivityCreated: async (payload, onComplete, onError) => {
        var _a;
        try {
            const { settings: { baseUrl, apiKey, fromPhoneNumber }, fields: { from, text, to }, } = (0, extensions_core_1.validate)({
                schema: zod_1.z
                    .object({
                    settings: settings_1.SettingsValidationSchema,
                    fields: config_1.FieldsValidationSchema,
                })
                    .superRefine((value, ctx) => {
                    if ((0, lodash_1.isEmpty)(value.fields.from) &&
                        (0, lodash_1.isEmpty)(value.settings.fromPhoneNumber)) {
                        ctx.addIssue({
                            code: zod_1.z.ZodIssueCode.custom,
                            fatal: true,
                            message: '"From" number is missing in both settings and in the action fields.',
                        });
                    }
                }),
                payload,
            });
            const client = new client_1.InfobipClient({ baseUrl, apiToken: apiKey });
            await client.smsApi.send({
                messages: [
                    {
                        destinations: [{ to }],
                        from: (_a = from !== null && from !== void 0 ? from : fromPhoneNumber) !== null && _a !== void 0 ? _a : '',
                        text,
                    },
                ],
            });
            await onComplete();
        }
        catch (err) {
            if ((0, error_1.isInfobipError)(err)) {
                const events = (0, error_1.infobipErrorToActivityEvent)(err);
                await onError({ events });
            }
            else {
                // re-throw to be handled in extensions server
                throw err;
            }
        }
    },
};
//# sourceMappingURL=sendSms.js.map