"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const actions_core_1 = require("@segment/actions-core");
const config_1 = require("./config");
const upsertProfile_1 = __importDefault(require("./upsertProfile"));
const addProfileToList_1 = __importDefault(require("./addProfileToList"));
const removeProfileFromList_1 = __importDefault(require("./removeProfileFromList"));
const trackEvent_1 = __importDefault(require("./trackEvent"));
const orderCompleted_1 = __importDefault(require("./orderCompleted"));
const subscribeProfile_1 = __importDefault(require("./subscribeProfile"));
const functions_1 = require("./functions");
const removeProfile_1 = __importDefault(require("./removeProfile"));
const unsubscribeProfile_1 = __importDefault(require("./unsubscribeProfile"));
const destination = {
    name: 'Klaviyo (Actions)',
    slug: 'actions-klaviyo',
    mode: 'cloud',
    authentication: {
        scheme: 'custom',
        fields: {
            api_key: {
                type: 'password',
                label: 'API Key',
                description: `You can find this by going to Klaviyo's UI and clicking Account > Settings > API Keys > Create API Key`,
                required: true
            }
        },
        testAuthentication: (request) => {
            return request(`${config_1.API_URL}/accounts/`, {
                method: 'get'
            });
        }
    },
    onDelete: async (request, { payload }) => {
        return request(`${config_1.API_URL}/data-privacy-deletion-jobs/`, {
            method: 'post',
            json: {
                data: {
                    type: 'data-privacy-deletion-job',
                    attributes: {
                        profile: {
                            data: {
                                type: 'profile',
                                id: payload.userId
                            }
                        }
                    }
                }
            }
        });
    },
    extendRequest({ settings }) {
        return {
            headers: (0, functions_1.buildHeaders)(settings.api_key)
        };
    },
    audienceFields: {
        listId: {
            label: 'List Id',
            description: `The default List ID to subscribe users to. This list takes precedence over the new list segment auto creates when attaching this destination to an audience.`,
            type: 'string'
        }
    },
    audienceConfig: {
        mode: {
            type: 'synced',
            full_audience_sync: false
        },
        async createAudience(request, createAudienceInput) {
            const audienceName = createAudienceInput.audienceName;
            const apiKey = createAudienceInput.settings.api_key;
            const defaultAudienceId = createAudienceInput.audienceSettings?.listId;
            if (defaultAudienceId) {
                return { externalId: defaultAudienceId };
            }
            if (!audienceName) {
                throw new actions_core_1.PayloadValidationError('Missing audience name value');
            }
            if (!apiKey) {
                throw new actions_core_1.PayloadValidationError('Missing Api Key value');
            }
            const response = await request(`${config_1.API_URL}/lists`, {
                method: 'POST',
                headers: (0, functions_1.buildHeaders)(apiKey),
                json: {
                    data: { type: 'list', attributes: { name: audienceName } }
                }
            });
            const r = await response.json();
            return {
                externalId: r.data.id
            };
        },
        async getAudience(request, getAudienceInput) {
            const defaultAudienceId = getAudienceInput.audienceSettings?.listId;
            if (defaultAudienceId) {
                getAudienceInput.externalId = defaultAudienceId;
            }
            const listId = getAudienceInput.externalId;
            const apiKey = getAudienceInput.settings.api_key;
            const response = await request(`${config_1.API_URL}/lists/${listId}`, {
                method: 'GET',
                headers: (0, functions_1.buildHeaders)(apiKey),
                throwHttpErrors: false
            });
            if (!response.ok) {
                const errorResponse = await response.json();
                const klaviyoErrorDetail = errorResponse.errors[0].detail;
                throw new actions_core_1.APIError(klaviyoErrorDetail, response.status);
            }
            const r = await response.json();
            const externalId = r.data.id;
            if (externalId !== getAudienceInput.externalId) {
                throw new actions_core_1.IntegrationError("Unable to verify ownership over audience. Segment Audience ID doesn't match The Klaviyo List Id.", 'INVALID_REQUEST_DATA', 400);
            }
            return {
                externalId
            };
        }
    },
    actions: {
        upsertProfile: upsertProfile_1.default,
        addProfileToList: addProfileToList_1.default,
        removeProfileFromList: removeProfileFromList_1.default,
        trackEvent: trackEvent_1.default,
        orderCompleted: orderCompleted_1.default,
        subscribeProfile: subscribeProfile_1.default,
        unsubscribeProfile: unsubscribeProfile_1.default,
        removeProfile: removeProfile_1.default
    },
    presets: [
        {
            name: 'Entities Audience Entered',
            partnerAction: 'addProfileToList',
            mapping: (0, actions_core_1.defaultValues)(addProfileToList_1.default.fields),
            type: 'specificEvent',
            eventSlug: 'warehouse_audience_entered_track'
        },
        {
            name: 'Entities Audience Exited',
            partnerAction: 'removeProfileFromList',
            mapping: (0, actions_core_1.defaultValues)(removeProfileFromList_1.default.fields),
            type: 'specificEvent',
            eventSlug: 'warehouse_audience_exited_track'
        },
        {
            name: 'Associated Entity Added',
            partnerAction: 'addProfileToList',
            mapping: (0, actions_core_1.defaultValues)(addProfileToList_1.default.fields),
            type: 'specificEvent',
            eventSlug: 'warehouse_entity_added_track'
        },
        {
            name: 'Associated Entity Removed',
            partnerAction: 'removeProfileFromList',
            mapping: (0, actions_core_1.defaultValues)(removeProfileFromList_1.default.fields),
            type: 'specificEvent',
            eventSlug: 'warehouse_entity_removed_track'
        },
        {
            name: 'Journeys Step Entered',
            partnerAction: 'addProfileToList',
            mapping: (0, actions_core_1.defaultValues)(addProfileToList_1.default.fields),
            type: 'specificEvent',
            eventSlug: 'journeys_step_entered_track'
        },
        {
            name: 'Journeys Step Entered',
            partnerAction: 'trackEvent',
            mapping: (0, actions_core_1.defaultValues)(trackEvent_1.default.fields),
            type: 'specificEvent',
            eventSlug: 'journeys_step_entered_track'
        },
        {
            name: 'Journeys Step Entered',
            partnerAction: 'orderCompleted',
            mapping: (0, actions_core_1.defaultValues)(orderCompleted_1.default.fields),
            type: 'specificEvent',
            eventSlug: 'journeys_step_entered_track'
        },
        {
            name: 'Journeys Step Entered',
            partnerAction: 'subscribeProfile',
            mapping: (0, actions_core_1.defaultValues)(subscribeProfile_1.default.fields),
            type: 'specificEvent',
            eventSlug: 'journeys_step_entered_track'
        },
        {
            name: 'Journeys Step Entered',
            partnerAction: 'unsubscribeProfile',
            mapping: (0, actions_core_1.defaultValues)(unsubscribeProfile_1.default.fields),
            type: 'specificEvent',
            eventSlug: 'journeys_step_entered_track'
        }
    ]
};
exports.default = destination;
//# sourceMappingURL=index.js.map