"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createOrUpdateContact = void 0;
const extensions_core_1 = require("@awell-health/extensions-core");
const lib_1 = require("../../lib");
const config_1 = require("./config");
const lodash_1 = require("lodash");
const addEventLog_1 = require("../../../../src/lib/awell/addEventLog");
const helpers_1 = require("./helpers");
exports.createOrUpdateContact = {
    key: 'createOrUpdateContact',
    category: extensions_core_1.Category.CUSTOMER_SUPPORT,
    title: 'Create or update contact',
    description: 'Create or update a contact in HubSpot',
    fields: config_1.fields,
    previewable: true,
    dataPoints: config_1.dataPoints,
    onEvent: async ({ payload, onComplete, onError, helpers }) => {
        const eventLogs = [];
        const { hubSpotSdk, fields } = await (0, lib_1.validatePayloadAndCreateSdks)({
            fieldsSchema: config_1.FieldsValidationSchema,
            payload,
        });
        const createOrUpdateProperties = {
            /**
             * Default Hubspot properties
             * Available in every Hubspot account
             */
            email: fields.email,
            ...(!(0, lodash_1.isNil)(fields.firstName) && { firstname: fields.firstName }),
            ...(!(0, lodash_1.isNil)(fields.lastName) && { lastname: fields.lastName }),
            ...(!(0, lodash_1.isNil)(fields.phone) && { phone: fields.phone }),
            /**
             * Custom properties
             */
            ...(!(0, lodash_1.isNil)(fields.customProperties) && fields.customProperties),
        };
        try {
            // Try retrieving an existing contact
            const existingContact = await (0, helpers_1.getExistingContact)(hubSpotSdk, fields.email);
            if (!(0, lodash_1.isNil)(existingContact)) {
                eventLogs.push((0, addEventLog_1.addActivityEventLog)({
                    message: `Existing contact found in Hubspot with email ${fields.email}. Contact ID: ${existingContact.id}`,
                }), (0, addEventLog_1.addActivityEventLog)({
                    message: `Existing contact details: ${JSON.stringify(existingContact, null, 2)}`,
                }));
                // Update the existing contact
                const updatedContact = await (0, helpers_1.updateContact)(hubSpotSdk, existingContact.id, createOrUpdateProperties);
                await onComplete({
                    data_points: {
                        hubspotContactId: updatedContact.id,
                        contactResource: JSON.stringify(updatedContact),
                    },
                    events: [
                        ...eventLogs,
                        (0, addEventLog_1.addActivityEventLog)({
                            message: `Updated contact:\n${JSON.stringify(updatedContact, null, 2)}`,
                        }),
                    ],
                });
                return;
            }
            // Contact not found, create a new one
            eventLogs.push((0, addEventLog_1.addActivityEventLog)({
                message: `No existing contact found in Hubspot with email ${fields.email}.`,
            }));
            const newContact = await (0, helpers_1.createContact)(hubSpotSdk, createOrUpdateProperties);
            await onComplete({
                data_points: {
                    hubspotContactId: newContact.id,
                    contactResource: JSON.stringify(newContact),
                },
                events: [
                    ...eventLogs,
                    (0, addEventLog_1.addActivityEventLog)({
                        message: `Contact created in Hubspot with email ${fields.email}. Contact ID: ${newContact.id}`,
                    }),
                    (0, addEventLog_1.addActivityEventLog)({
                        message: `New contact:\n${JSON.stringify(newContact, null, 2)}`,
                    }),
                ],
            });
        }
        catch (err) {
            const typedError = err;
            await onError({
                events: [
                    ...eventLogs,
                    (0, addEventLog_1.addActivityEventLog)({
                        message: `Error in Hubspot operation: ${typedError.code}: ${typedError.message}\n${JSON.stringify(typedError.body, null, 2)}`,
                    }),
                ],
            });
        }
    },
};
//# sourceMappingURL=createOrUpdateContact.js.map