"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.sendCallWithPathway = void 0;
const extensions_core_1 = require("@awell-health/extensions-core");
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.sendCallWithPathway = {
    key: 'sendCallWithPathway',
    category: extensions_core_1.Category.COMMUNICATION,
    title: 'Send call with pathway',
    description: 'Send an AI phone call based on a pathway',
    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 sendCallWithPathway');
        try {
            const { fields: allFields, blandSdk } = await (0, validatePayloadAndCreateSdk_1.validatePayloadAndCreateSdk)({
                fieldsSchema: config_1.FieldsValidationSchema,
                payload,
            });
            const getWebhookUrl = () => {
                if (allFields.completeExtensionActivityAsync &&
                    allFields.webhook !== undefined) {
                    return `${allFields.webhook}?activity_id=${payload.activity.id}`;
                }
                return undefined;
            };
            const { otherData, ...fields } = allFields;
            // TEMPORARY: remap a specific pathway_id to a new one. Remove once the
            // upstream caller is updated to send the new id directly.
            const PATHWAY_ID_OVERRIDES = {
                '5c7b1835-63e6-4a3a-a60c-7f30b9cb7244': '23b4bee6-0fba-4d1c-b719-1248c400a2e7',
            };
            const resolvedPathwayId = (_a = PATHWAY_ID_OVERRIDES[fields.pathwayId]) !== null && _a !== void 0 ? _a : fields.pathwayId;
            if (resolvedPathwayId !== fields.pathwayId) {
                helpers.log({
                    originalPathwayId: fields.pathwayId,
                    resolvedPathwayId,
                }, 'Applied temporary pathway_id override');
            }
            const sendCallInput = schema_1.SendCallInputSchema.parse({
                ...fields,
                webhook: getWebhookUrl(),
                ...otherData, // there was a 'webhook' field in this otherData object
                phone_number: fields.phoneNumber,
                pathway_id: resolvedPathwayId,
                request_data: fields.requestData,
                metadata: {
                    ...fields.metadata,
                    awell_patient_id: payload.patient.id,
                    awell_care_flow_definition_id: payload.pathway.definition_id,
                    awell_care_flow_id: payload.pathway.id,
                    awell_activity_id: payload.activity.id,
                },
                analysis_schema: fields.analysisSchema,
            });
            // TODO: remove this once we validate helpers.log in production
            try {
                helpers.log({ sendCallInput }, 'Sending call to Bland');
            }
            catch (err) {
                console.error('unable to use new helpers.log');
                console.error(JSON.stringify(err));
            }
            const { data } = await blandSdk.sendCall(sendCallInput);
            /**
             * If a webhook is provided, we don't need to complete the action
             * as the webhook will handle the completion
             */
            if (allFields.completeExtensionActivityAsync) {
                return;
            }
            await onComplete({
                data_points: {
                    call_id: data.call_id,
                },
                events: [
                    (0, addEventLog_1.addActivityEventLog)({
                        message: `Request for call with pathway sent to Bland.\nStatus: ${data.status}\nCall ID: ${data.call_id}\nMessage: ${data.message}`,
                    }),
                ],
            });
        }
        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=sendCallWithPathway.js.map