"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.sendMessageToChannel = void 0;
const extensions_core_1 = require("@awell-health/extensions-core");
const zod_1 = require("zod");
const settings_1 = require("../../../settings");
const config_1 = require("./config");
const client_1 = require("../../../client");
const getCareFlowUrl = (pathwayId) => {
    var _a;
    const environment = (_a = process.env.AWELL_ENVIRONMENT) !== null && _a !== void 0 ? _a : '';
    const envDomain = environment !== '' ? `.${environment}` : '';
    return `https://care${envDomain}.awellhealth.com/pathway/${pathwayId}/activity-feed`;
};
exports.sendMessageToChannel = {
    key: 'sendMessageToChannel',
    title: 'Send Message to Channel',
    description: 'Send a message to a Slack channel.',
    category: extensions_core_1.Category.COMMUNICATION,
    fields: config_1.fields,
    dataPoints: config_1.dataPoints,
    previewable: true,
    onEvent: async ({ payload, onComplete, onError }) => {
        var _a, _b, _c;
        try {
            const { settings: { botToken }, fields: { channel, message }, } = (0, extensions_core_1.validate)({
                schema: zod_1.z.object({
                    settings: settings_1.SettingsValidationSchema,
                    fields: config_1.FieldsValidationSchema,
                }),
                payload,
            });
            const slackClient = new client_1.SlackClient({ botToken });
            const careFlowUrl = getCareFlowUrl(payload.pathway.id);
            const messageWithLink = `${message}\n\n<${careFlowUrl}|View Care Flow>`;
            const response = await slackClient.postMessage({
                channel,
                text: messageWithLink,
            });
            await onComplete({
                data_points: {
                    messageTs: (_a = response.ts) !== null && _a !== void 0 ? _a : '',
                    channelId: (_b = response.channel) !== null && _b !== void 0 ? _b : '',
                },
                events: [
                    {
                        date: new Date().toISOString(),
                        text: {
                            en: `Message sent to channel ${(_c = response.channel) !== null && _c !== void 0 ? _c : channel}`,
                        },
                    },
                ],
            });
        }
        catch (error) {
            if ((0, client_1.isSlackErrorResponse)(error)) {
                await onError({
                    events: [(0, client_1.mapSlackErrorToActivityEvent)(error)],
                });
            }
            else {
                throw error;
            }
        }
    },
};
//# sourceMappingURL=sendMessageToChannel.js.map