"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaboolaClient = void 0;
const crypto_1 = require("crypto");
const actions_core_1 = require("@segment/actions-core");
class TaboolaClient {
    constructor(request, payloads, audienceSettings) {
        this.request = request;
        this.payloads = payloads;
        this.audienceSettings = audienceSettings;
        if (!this.audienceSettings) {
            throw new actions_core_1.IntegrationError('Bad Request: no audienceSettings found.', 'INVALID_REQUEST_DATA', 400);
        }
        if (!this.audienceSettings.account_id) {
            throw new actions_core_1.IntegrationError('Bad Request: no audienceSettings.account_id found.', 'INVALID_REQUEST_DATA', 400);
        }
    }
    static async refreshAccessToken(request, settings) {
        const res = await request('https://backstage.taboola.com/backstage/oauth/token', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: String(new URLSearchParams({
                client_id: settings.client_id,
                client_secret: settings.client_secret,
                grant_type: 'client_credentials'
            }))
        });
        return { accessToken: res.data.access_token };
    }
    async sendToTaboola() {
        this.payloads.forEach((payload) => {
            payload.action = payload.traits_or_props[payload.segment_computation_key] ? 'ADD' : 'REMOVE';
        });
        const actionMap = new Map();
        this.payloads.forEach((payload) => {
            if (!actionMap.has(payload.action)) {
                actionMap.set(payload.action, new Map());
            }
            const audienceMap = actionMap.get(payload.action);
            if (!audienceMap.has(payload.external_audience_id)) {
                audienceMap.set(payload.external_audience_id, []);
            }
            audienceMap.get(payload.external_audience_id)?.push(payload);
        });
        const taboolaRequests = [];
        actionMap.forEach((audienceMap, action) => {
            audienceMap.forEach((payloads, external_audience_id) => {
                const identities = payloads.map((payload) => this.createCluster(payload)).filter((cluster) => cluster !== null);
                if (identities.length > 0) {
                    taboolaRequests.push(this.request(`https://backstage.taboola.com/backstage/api/1.0/${this.audienceSettings?.account_id}/audience_onboarding`, {
                        method: 'POST',
                        json: {
                            operation: action,
                            audience_id: Number(external_audience_id),
                            identities,
                            integration_source: 'segment.com'
                        }
                    }));
                }
            });
        });
        if (taboolaRequests.length === 0) {
            throw new actions_core_1.IntegrationError('No valid payloads found to sync.', 'INVALID_REQUEST_DATA', 400);
        }
        return await Promise.all(taboolaRequests);
    }
    hashEmail(email) {
        const sha256HashedRegex = /^[a-f0-9]{64}$/i;
        const isSHA256Hash = sha256HashedRegex.test(email);
        if (!isSHA256Hash) {
            email = (0, crypto_1.createHash)('sha256').update(email).digest('hex');
        }
        return email;
    }
    createCluster(payload) {
        if (!payload.user_email && !payload.device_id) {
            return null;
        }
        let email = payload.user_email;
        const cluster = [];
        if (email) {
            email = this.hashEmail(email);
            cluster.push({
                user_id: email,
                type: 'EMAIL_ID',
                is_hashed: true
            });
        }
        if (payload.device_id) {
            cluster.push({
                user_id: payload.device_id,
                type: 'DEVICE_ID',
                is_hashed: false
            });
        }
        return { cluster };
    }
}
exports.TaboolaClient = TaboolaClient;
//# sourceMappingURL=client.js.map