"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.sendCampaign = void 0;
const zod_1 = require("zod");
const lodash_1 = require("lodash");
const extensions_core_1 = require("@awell-health/extensions-core");
const settings_1 = require("../../settings");
const client_1 = require("../../client");
const config_1 = require("./config");
exports.sendCampaign = {
    key: 'sendCampaign',
    title: 'Send campaign',
    description: 'Send a campaign with Braze',
    category: extensions_core_1.Category.COMMUNICATION,
    fields: config_1.fields,
    dataPoints: config_1.dataPoints,
    previewable: false,
    onEvent: async ({ payload, onComplete, onError, helpers }) => {
        const { fields: { externalUserId: external_user_id, sendId: send_id, email, campaignId: campaign_id, triggerProperties: trigger_properties, attributes, }, settings: { apiKey, baseUrl }, } = (0, extensions_core_1.validate)({
            schema: zod_1.z.object({
                fields: config_1.FieldsSchema,
                settings: settings_1.SettingsValidationSchema,
            }),
            payload,
        });
        if ((0, lodash_1.isNil)(external_user_id) && (0, lodash_1.isNil)(email)) {
            throw new Error('Either externalUserId or email must be provided.');
        }
        const client = new client_1.BrazeClient({ apiKey, baseUrl });
        const requestBody = {
            campaign_id,
            recipients: [
                {
                    ...(!(0, lodash_1.isNil)(external_user_id) && {
                        external_user_id,
                    }),
                    ...(!(0, lodash_1.isNil)(email) && {
                        email,
                    }),
                    ...(!(0, lodash_1.isNil)(trigger_properties) && {
                        trigger_properties,
                    }),
                    ...(!(0, lodash_1.isNil)(attributes) && {
                        attributes,
                    }),
                },
            ],
            ...(!(0, lodash_1.isNil)(send_id) && {
                send_id,
            }),
        };
        const resp = await client.sendCampaign(requestBody);
        await onComplete({
            events: [
                {
                    date: new Date().toISOString(),
                    text: { en: `Email sent. Response: ${JSON.stringify(resp)}` },
                },
            ],
            data_points: {
                EmailDispatchId: resp.dispatch_id,
            },
        });
    },
};
//# sourceMappingURL=sendCampaign.js.map