"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const functions_1 = require("../functions");
const actions_core_1 = require("@segment/actions-core");
const functions_2 = require("../functions");
const config_1 = require("../config");
const properties_1 = require("../properties");
const action = {
    title: 'Unsubscribe Profile',
    defaultSubscription: 'type = "track" and event = "User Unsubscribed"',
    description: 'Unsubscribe Klaviyo profiles from Email marketing, SMS marketing, or both.',
    fields: {
        email: {
            label: 'Email',
            description: `The email address to unsubscribe. If provided, the associated profile will be unsubscribed to Email marketing.`,
            type: 'string',
            format: 'email',
            default: {
                '@if': {
                    exists: { '@path': '$.traits.email' },
                    then: { '@path': '$.traits.email' },
                    else: { '@path': '$.context.traits.email' }
                }
            }
        },
        phone_number: {
            label: 'Phone Number',
            description: `The phone number to unsubscribe. This must be in E.164 format. If provided, the associated profile will be unsubscribed to SMS marketing.`,
            type: 'string',
            default: {
                '@if': {
                    exists: { '@path': '$.traits.phone' },
                    then: { '@path': '$.traits.phone' },
                    else: { '@path': '$.context.traits.phone' }
                }
            }
        },
        country_code: {
            ...properties_1.country_code
        },
        list_id: {
            label: 'List Id',
            description: `The Klaviyo list to remove the subscribed profiles from. If no list id is provided, the profile will be unsubscribed from all channels.`,
            type: 'string',
            dynamic: true
        },
        enable_batching: {
            type: 'boolean',
            label: 'Batch Data to Klaviyo',
            description: 'When enabled, the action will use the Klaviyo batch API.'
        },
        batch_keys: {
            label: 'Batch Keys',
            description: 'The keys to use for batching the events.',
            type: 'string',
            unsafe_hidden: true,
            required: false,
            multiple: true,
            default: ['list_id']
        }
    },
    dynamicFields: {
        list_id: async (request) => {
            return (0, functions_1.getListIdDynamicData)(request);
        }
    },
    perform: async (request, { payload }) => {
        const { email, phone_number: initialPhoneNumber, list_id, country_code } = payload;
        const phone_number = (0, functions_1.processPhoneNumber)(initialPhoneNumber, country_code);
        if (!email && !phone_number) {
            throw new actions_core_1.PayloadValidationError('Phone Number or Email is required.');
        }
        const profileToUnSubscribe = (0, functions_2.formatUnsubscribeProfile)(email, phone_number);
        const unSubData = (0, functions_2.formatUnsubscribeRequestBody)(profileToUnSubscribe, list_id);
        return await request(`${config_1.API_URL}/profile-subscription-bulk-delete-jobs`, {
            method: 'POST',
            json: unSubData
        });
    },
    performBatch: async (request, { payload, statsContext }) => {
        const filteredPayload = payload.filter((profile) => {
            const validPhoneNumber = (0, functions_1.validateAndConvertPhoneNumber)(profile.phone_number, profile.country_code);
            if (validPhoneNumber) {
                profile.phone_number = validPhoneNumber;
            }
            else if (validPhoneNumber === null) {
                return false;
            }
            return profile.email || profile.phone_number;
        });
        if (statsContext) {
            const { statsClient, tags } = statsContext;
            const set = new Set();
            filteredPayload.forEach((profile) => {
                set.add(profile.list_id);
            });
            statsClient?.histogram('actions-klaviyo.unsubscribe_profile.unique_list_id', set.size, tags);
        }
        if (payload.length === 0) {
            throw new actions_core_1.PayloadValidationError('Phone Number or Email is required.');
        }
        const sortedProfilesObject = sortBatches(filteredPayload);
        const batches = Object.keys(sortedProfilesObject);
        if (batches.length > 9) {
            throw new actions_core_1.PayloadValidationError('Exceeded maximum allowed batches due to too many unique list_ids');
        }
        const requests = [];
        batches.forEach((key) => {
            const { list_id, profiles } = sortedProfilesObject[key];
            for (let i = 0; i < profiles.length; i += 100) {
                const profilesSubset = profiles.slice(i, i + 100);
                const unSubData = (0, functions_2.formatUnsubscribeRequestBody)(profilesSubset, list_id);
                const response = request(`${config_1.API_URL}/profile-subscription-bulk-delete-jobs`, {
                    method: 'POST',
                    json: unSubData
                });
                requests.push(response);
            }
        });
        return await Promise.all(requests);
    }
};
exports.default = action;
function sortBatches(batchPayload) {
    const output = {};
    batchPayload.forEach((payload) => {
        const { email, phone_number, list_id } = payload;
        const key = list_id || 'noListId';
        if (!output[key]) {
            const batch = {
                profiles: []
            };
            if (list_id !== undefined) {
                batch.list_id = list_id;
            }
            output[key] = batch;
        }
        const profileToUnSubscribe = (0, functions_2.formatUnsubscribeProfile)(email, phone_number);
        output[key].profiles.push(profileToUnSubscribe);
    });
    return output;
}
//# sourceMappingURL=index.js.map