"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createLead = void 0;
const extensions_core_1 = require("@awell-health/extensions-core");
const config_1 = require("./config");
const lib_1 = require("../../lib");
const errors_1 = require("../../lib/errors");
const lodash_1 = require("lodash");
const addEventLog_1 = require("../../../../src/lib/awell/addEventLog");
exports.createLead = {
    key: 'createLead',
    category: extensions_core_1.Category.CUSTOMER_SUPPORT,
    title: 'Create lead',
    description: 'Creates a new lead object in Salesforce',
    fields: config_1.fields,
    previewable: false,
    dataPoints: config_1.dataPoints,
    onActivityCreated: async (payload, onComplete, onError) => {
        const { fields, pathwayId, salesforceClient } = await (0, lib_1.validatePayloadAndCreateClient)({
            fieldsSchema: config_1.FieldsValidationSchema,
            payload,
        });
        const data = {
            ...fields.data,
            ...(!(0, lodash_1.isNil)(fields.careFlowIdField) && {
                [fields.careFlowIdField]: pathwayId,
            }),
        };
        try {
            const res = await salesforceClient.createRecord({
                sObject: 'Lead',
                data,
            });
            await onComplete({
                data_points: {
                    createdLeadId: String(res.id),
                },
                events: [
                    (0, addEventLog_1.addActivityEventLog)({
                        message: `Lead with ID ${String(res.id)} created in Saleforce. Data passed:\n\n ${JSON.stringify(data, null, 2)}`,
                    }),
                ],
            });
        }
        catch (error) {
            if ((0, errors_1.isSalesforceError)(error)) {
                await onError({
                    events: [(0, errors_1.parseSalesforceError)(error)],
                });
            }
            else {
                // we handle ZodError and unknown errors in extension-server directly
                throw error;
            }
        }
    },
};
//# sourceMappingURL=createLead.js.map