"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createSmsConversation = void 0;
const extensions_core_1 = require("@awell-health/extensions-core");
const crypto_1 = require("crypto");
const lodash_1 = require("lodash");
const validatePayloadAndCreateSdk_1 = require("../../lib/validatePayloadAndCreateSdk");
const config_1 = require("./config");
const schema_1 = require("../../api/schema");
const addEventLog_1 = require("../../../../src/lib/awell/addEventLog");
exports.createSmsConversation = {
    key: 'createSmsConversation',
    category: extensions_core_1.Category.COMMUNICATION,
    title: 'Create SMS conversation',
    description: 'Create an SMS conversation seeded with pathway state, without sending a message immediately. The pathway then drives outbound texts.',
    fields: config_1.fields,
    previewable: true,
    dataPoints: config_1.dataPoints,
    supports_automated_retries: true,
    onEvent: async ({ payload, onComplete, onError, helpers }) => {
        var _a;
        helpers.log({ fields: payload.fields }, 'Processing createSmsConversation');
        try {
            const { fields, blandSdk } = await (0, validatePayloadAndCreateSdk_1.validatePayloadAndCreateSdk)({
                fieldsSchema: config_1.FieldsValidationSchema,
                payload,
            });
            const createSmsConversationInput = schema_1.CreateSmsConversationInputSchema.parse({
                user_number: fields.userNumber,
                agent_number: fields.agentNumber,
                message: fields.message,
                // Required by the live Bland API despite being documented as optional;
                // it is only a correlation id so a generated UUID is sufficient.
                message_sid: (0, crypto_1.randomUUID)(),
                sender: fields.sender,
                curr_pathway_id: (0, lodash_1.isEmpty)(fields.currPathwayId)
                    ? undefined
                    : fields.currPathwayId,
                curr_pathway_version: (0, lodash_1.isEmpty)(fields.currPathwayVersion)
                    ? undefined
                    : fields.currPathwayVersion,
                current_node_id: (0, lodash_1.isEmpty)(fields.currentNodeId)
                    ? undefined
                    : fields.currentNodeId,
                new_conversation: fields.newConversation,
                request_data: (0, lodash_1.isEmpty)(fields.requestData)
                    ? undefined
                    : fields.requestData,
            });
            try {
                helpers.log({ createSmsConversationInput }, 'Creating SMS conversation via Bland');
            }
            catch (err) {
                console.error('unable to use new helpers.log');
                console.error(JSON.stringify(err));
            }
            const { data } = await blandSdk.createSmsConversation(createSmsConversationInput);
            const conversationId = (_a = data === null || data === void 0 ? void 0 : data.data) === null || _a === void 0 ? void 0 : _a.conversation_id;
            await onComplete({
                data_points: {
                    conversationId: (0, lodash_1.isNil)(conversationId) ? undefined : conversationId,
                    createResponse: (0, lodash_1.isNil)(data) ? undefined : JSON.stringify(data),
                },
                events: [
                    (0, addEventLog_1.addActivityEventLog)({
                        message: `SMS conversation created in Bland.\nConversation ID: ${conversationId !== null && conversationId !== void 0 ? conversationId : 'n/a'}`,
                    }),
                ],
            });
        }
        catch (err) {
            helpers.log({ err }, 'error', err);
            const error = err;
            await onError({
                events: [
                    {
                        date: new Date().toISOString(),
                        text: { en: error.message },
                        error: {
                            category: 'SERVER_ERROR',
                            message: error.message,
                        },
                    },
                ],
            });
        }
    },
};
//# sourceMappingURL=createSmsConversation.js.map