"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.sendEmailWithTemplate = 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 error_1 = require("../../client/error");
const client_1 = require("../../client");
exports.sendEmailWithTemplate = {
    key: 'sendEmailWithTemplate',
    title: 'Send email with template',
    description: 'Sends email with a template using Infobip',
    category: extensions_core_1.Category.COMMUNICATION,
    fields: config_1.fields,
    previewable: true,
    onActivityCreated: async (payload, onComplete, onError) => {
        try {
            const { settings: { baseUrl, apiKey }, fields: { to, subject, templateId, placeholders }, } = (0, extensions_core_1.validate)({
                schema: zod_1.z.object({
                    settings: settings_1.SettingsValidationSchema,
                    fields: config_1.FieldsValidationSchema,
                }),
                payload,
            });
            const client = new client_1.InfobipClient({ baseUrl, apiToken: apiKey });
            await client.emailApi.send({
                to: [to],
                subject,
                templateId,
                defaultPlaceholders: JSON.stringify(placeholders),
            });
            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=sendEmailWithTemplate.js.map