"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const actions_core_1 = require("@segment/actions-core");
const sf_properties_1 = require("../sf-properties");
const sf_operations_1 = __importStar(require("../sf-operations"));
const OBJECT_NAME = 'Lead';
const action = {
    title: 'Lead V2',
    description: 'Create, update, or upsert leads in Salesforce.',
    defaultSubscription: 'type = "identify"',
    syncMode: {
        description: 'Define how the records from your destination will be synced.',
        label: 'How to sync records',
        default: 'add',
        choices: [
            { label: 'Insert Records', value: 'add' },
            { label: 'Update Records', value: 'update' },
            { label: 'Upsert Records', value: 'upsert' },
            { label: 'Delete Records. Not available when using batching. Requests will result in errors.', value: 'delete' }
        ]
    },
    fields: {
        recordMatcherOperator: sf_properties_1.recordMatcherOperator2,
        enable_batching: sf_properties_1.enable_batching2,
        batch_size: sf_properties_1.batch_size2,
        traits: sf_properties_1.traits2,
        bulkUpsertExternalId: sf_properties_1.bulkUpsertExternalId2,
        bulkUpdateRecordId: sf_properties_1.bulkUpdateRecordId2,
        customFields: sf_properties_1.customFields2,
        company: {
            label: 'Company',
            description: "The lead's company. **This is required to create a lead.**",
            type: 'string',
            default: {
                '@if': {
                    exists: { '@path': '$.traits.company' },
                    then: { '@path': '$.traits.company' },
                    else: { '@path': '$.properties.company' }
                }
            },
            depends_on: sf_properties_1.hideIfDeleteSyncMode
        },
        last_name: {
            label: 'Last Name',
            description: "The lead's last name. **This is required to create a lead.**",
            type: 'string',
            default: {
                '@if': {
                    exists: { '@path': '$.traits.last_name' },
                    then: { '@path': '$.traits.last_name' },
                    else: { '@path': '$.properties.last_name' }
                }
            },
            depends_on: sf_properties_1.hideIfDeleteSyncMode
        },
        first_name: {
            label: 'First Name',
            description: "The lead's first name.",
            type: 'string',
            default: {
                '@if': {
                    exists: { '@path': '$.traits.first_name' },
                    then: { '@path': '$.traits.first_name' },
                    else: { '@path': '$.properties.first_name' }
                }
            },
            depends_on: sf_properties_1.hideIfDeleteSyncMode
        },
        email: {
            label: 'Email',
            description: "The lead's email address.",
            type: 'string',
            default: {
                '@if': {
                    exists: { '@path': '$.traits.email' },
                    then: { '@path': '$.traits.email' },
                    else: { '@path': '$.properties.email' }
                }
            },
            depends_on: sf_properties_1.hideIfDeleteSyncMode
        },
        city: {
            label: 'City',
            description: "City for the lead's address.",
            type: 'string',
            default: {
                '@if': {
                    exists: { '@path': '$.traits.address.city' },
                    then: { '@path': '$.traits.address.city' },
                    else: { '@path': '$.properties.address.city' }
                }
            },
            depends_on: sf_properties_1.hideIfDeleteSyncMode
        },
        postal_code: {
            label: 'Postal Code',
            description: "Postal code for the lead's address.",
            type: 'string',
            default: {
                '@if': {
                    exists: { '@path': '$.traits.address.postal_code' },
                    then: { '@path': '$.traits.address.postal_code' },
                    else: { '@path': '$.properties.address.postal_code' }
                }
            },
            depends_on: sf_properties_1.hideIfDeleteSyncMode
        },
        country: {
            label: 'Country',
            description: "Country for the lead's address.",
            type: 'string',
            default: {
                '@if': {
                    exists: { '@path': '$.traits.address.country' },
                    then: { '@path': '$.traits.address.country' },
                    else: { '@path': '$.properties.address.country' }
                }
            },
            depends_on: sf_properties_1.hideIfDeleteSyncMode
        },
        street: {
            label: 'Street',
            description: "Street number and name for the lead's address.",
            type: 'string',
            default: {
                '@if': {
                    exists: { '@path': '$.traits.address.street' },
                    then: { '@path': '$.traits.address.street' },
                    else: { '@path': '$.properties.address.street' }
                }
            },
            depends_on: sf_properties_1.hideIfDeleteSyncMode
        },
        state: {
            label: 'State',
            description: "State for the lead's address.",
            type: 'string',
            default: {
                '@if': {
                    exists: { '@path': '$.traits.address.state' },
                    then: { '@path': '$.traits.address.state' },
                    else: { '@path': '$.properties.address.state' }
                }
            },
            depends_on: sf_properties_1.hideIfDeleteSyncMode
        }
    },
    perform: async (request, { settings, payload, syncMode }) => {
        const sf = new sf_operations_1.default(settings.instanceUrl, await (0, sf_operations_1.generateSalesforceRequest)(settings, request));
        if (syncMode === 'add') {
            if (!payload.last_name) {
                throw new actions_core_1.IntegrationError('Missing last_name value', 'Misconfigured required field', 400);
            }
            return await sf.createRecord(payload, OBJECT_NAME);
        }
        (0, sf_properties_1.validateLookup2)(syncMode, payload);
        if (syncMode === 'update') {
            return await sf.updateRecord(payload, OBJECT_NAME);
        }
        if (syncMode === 'upsert') {
            if (!payload.last_name) {
                throw new actions_core_1.IntegrationError('Missing last_name value', 'Misconfigured required field', 400);
            }
            return await sf.upsertRecord(payload, OBJECT_NAME);
        }
        if (syncMode === 'delete') {
            return await sf.deleteRecord(payload, OBJECT_NAME);
        }
    },
    performBatch: async (request, { settings, payload, syncMode, features, statsContext, logger }) => {
        const sf = new sf_operations_1.default(settings.instanceUrl, await (0, sf_operations_1.generateSalesforceRequest)(settings, request));
        if (syncMode === 'upsert') {
            if (!payload[0].last_name) {
                throw new actions_core_1.IntegrationError('Missing last_name value', 'Misconfigured required field', 400);
            }
        }
        let shouldShowAdvancedLogging = false;
        if (features && features['salesforce-advanced-logging']) {
            shouldShowAdvancedLogging = true;
        }
        return sf.bulkHandlerWithSyncMode(payload, OBJECT_NAME, syncMode, {
            shouldLog: shouldShowAdvancedLogging,
            stats: statsContext,
            logger
        });
    }
};
exports.default = action;
//# sourceMappingURL=index.js.map