"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.processPayload = processPayload;
const actions_core_1 = require("@segment/actions-core");
const api_1 = require("../api");
const hashing_utils_1 = require("../../../lib/hashing-utils");
async function processPayload(request, settings, payloads, statsContext) {
    validate(settings, payloads);
    const linkedinApiClient = new api_1.LinkedInAudiences(request);
    const dmpSegmentId = await getDmpSegmentId(linkedinApiClient, settings, payloads[0], statsContext);
    const elements = extractUsers(settings, payloads);
    if (elements.length < 1) {
        return;
    }
    statsContext?.statsClient?.incr('oauth_app_api_call', 1, [
        ...statsContext?.tags,
        `endpoint:add-or-remove-users-from-dmpSegment`
    ]);
    const res = await linkedinApiClient.batchUpdate(dmpSegmentId, elements);
    if (res.status !== 200) {
        throw new actions_core_1.RetryableError('Error while attempting to update LinkedIn DMP Segment. This batch will be retried.');
    }
    return res;
}
function validate(settings, payloads) {
    const isAutoOrUndefined = ['AUTO', undefined].includes(payloads[0]?.dmp_user_action);
    if (isAutoOrUndefined && payloads[0].source_segment_id !== payloads[0].personas_audience_key) {
        throw new actions_core_1.IntegrationError('The value of `source_segment_id` and `personas_audience_key` must match.', 'INVALID_SETTINGS', 400);
    }
    if (!settings.send_google_advertising_id && !settings.send_email) {
        throw new actions_core_1.IntegrationError('At least one of `Send Email` or `Send Google Advertising ID` must be set to `true`.', 'INVALID_SETTINGS', 400);
    }
}
async function getDmpSegmentId(linkedinApiClient, settings, payload, statsContext) {
    statsContext?.statsClient?.incr('oauth_app_api_call', 1, [...statsContext?.tags, `endpoint:get-dmpSegment`]);
    const res = await linkedinApiClient.getDmpSegment(settings, payload);
    const body = await res.json();
    if (body.elements?.length > 0) {
        return body.elements[0].id;
    }
    return createDmpSegment(linkedinApiClient, settings, payload, statsContext);
}
async function createDmpSegment(linkedinApiClient, settings, payload, statsContext) {
    statsContext?.statsClient?.incr('oauth_app_api_call', 1, [...statsContext?.tags, `endpoint:create-dmpSegment`]);
    const res = await linkedinApiClient.createDmpSegment(settings, payload);
    const headers = res.headers.toJSON();
    return headers['x-linkedin-id'];
}
function extractUsers(settings, payloads) {
    const elements = [];
    payloads.forEach((payload) => {
        if (!payload.email && !payload.google_advertising_id) {
            return;
        }
        const linkedinAudiencePayload = {
            action: getAction(payload),
            userIds: getUserIds(settings, payload)
        };
        if (payload.first_name) {
            linkedinAudiencePayload.firstName = payload.first_name;
        }
        if (payload.last_name) {
            linkedinAudiencePayload.lastName = payload.last_name;
        }
        if (payload.title) {
            linkedinAudiencePayload.title = payload.title;
        }
        if (payload.company) {
            linkedinAudiencePayload.company = payload.company;
        }
        if (payload.country) {
            linkedinAudiencePayload.country = payload.country;
        }
        elements.push(linkedinAudiencePayload);
    });
    return elements;
}
function getAction(payload) {
    const { dmp_user_action = 'AUTO' } = payload;
    if (dmp_user_action === 'ADD') {
        return 'ADD';
    }
    if (dmp_user_action === 'REMOVE') {
        return 'REMOVE';
    }
    if (dmp_user_action === 'AUTO' || !dmp_user_action) {
        if (payload.event_name === 'Audience Entered') {
            return 'ADD';
        }
        if (payload.event_name === 'Audience Exited') {
            return 'REMOVE';
        }
    }
    return 'ADD';
}
function getUserIds(settings, payload) {
    const userIds = [];
    if (payload.email && settings.send_email === true) {
        userIds.push({
            idType: 'SHA256_EMAIL',
            idValue: (0, hashing_utils_1.processHashing)(payload.email, 'sha256', 'hex')
        });
    }
    if (payload.google_advertising_id && settings.send_google_advertising_id === true) {
        userIds.push({
            idType: 'GOOGLE_AID',
            idValue: payload.google_advertising_id
        });
    }
    return userIds;
}
//# sourceMappingURL=functions.js.map