"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getMessages = void 0;
const zod_1 = require("zod");
const zod_validation_error_1 = require("zod-validation-error");
const settings_1 = require("../../settings");
const extensions_core_1 = require("@awell-health/extensions-core");
const config_1 = require("./config");
const textLineApi_1 = __importDefault(require("../../client/textLineApi"));
const lodash_1 = require("lodash");
exports.getMessages = {
    key: 'getMessages',
    title: 'Get messages',
    description: `
    Get a list of text messages matching the given criteria.
    You can also filter the Messages by providing one of the allowed filters.
    `,
    category: extensions_core_1.Category.COMMUNICATION,
    fields: config_1.fields,
    dataPoints: config_1.dataPoints,
    previewable: true,
    onActivityCreated: async (payload, onComplete, onError) => {
        try {
            const { settings: { accessToken }, fields: { phoneNumber, afterMessageId, departmentId }, } = (0, extensions_core_1.validate)({
                schema: zod_1.z.object({
                    settings: settings_1.SettingsValidationSchema,
                    fields: config_1.FieldsValidationSchema,
                }),
                payload,
            });
            const textLineApi = new textLineApi_1.default(accessToken);
            const messages = await textLineApi.getMessages(phoneNumber, afterMessageId, departmentId, 1, 30);
            if ((0, lodash_1.isNil)(messages.posts)) {
                await onComplete({
                    data_points: {
                        allMessages: '',
                        numberOfMessages: '0',
                        undefined,
                    },
                });
            }
            else {
                // received messages contain a phone number, sent messages will not
                const receivedMessages = messages.posts.filter((p) => !(0, lodash_1.isNil)(p.creator.phone_number)).sort((a, b) => {
                    return b.created_at - a.created_at;
                });
                const numberOfMessages = receivedMessages.length;
                const allMessages = receivedMessages.map(function (p) {
                    return p.body;
                });
                const latestMessage = numberOfMessages > 0 ? receivedMessages[0].body : undefined;
                await onComplete({
                    data_points: {
                        allMessages: JSON.stringify(allMessages),
                        numberOfMessages: String(numberOfMessages),
                        latestMessage,
                    },
                });
            }
        }
        catch (err) {
            if (err instanceof zod_1.ZodError) {
                const error = (0, zod_validation_error_1.fromZodError)(err);
                await onError({
                    events: [
                        {
                            date: new Date().toISOString(),
                            text: { en: error.message },
                            error: {
                                category: 'BAD_REQUEST',
                                message: error.message,
                            },
                        },
                    ],
                });
            }
            else {
                const message = err.message;
                await onError({
                    events: [
                        {
                            date: new Date().toISOString(),
                            text: { en: message },
                            error: {
                                category: 'SERVER_ERROR',
                                message,
                            },
                        },
                    ],
                });
            }
        }
    },
};
//# sourceMappingURL=getMessages.js.map