"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const actions_core_1 = require("@segment/actions-core");
const utils_rt_1 = require("../utils-rt");
const constants_1 = require("../constants");
const action = {
    title: 'Sync To Delivr AI Audience Segmentation',
    description: 'Sync Segment Audience to Delivr AI Audience Segmentation.',
    defaultSubscription: 'type = "identify" or type = "track"',
    fields: {
        segment_audience_id: {
            label: 'Segment Audience Id',
            description: 'Segment Audience Id (aud_...). Maps to "Id" of a Segment node in Delivr AI Audience Segment.',
            type: 'string',
            unsafe_hidden: false,
            required: false,
            default: {
                '@path': '$.context.personas.computation_id'
            }
        },
        email: {
            label: 'User Email',
            description: 'Email address of a user.',
            type: 'string',
            unsafe_hidden: false,
            required: true,
            default: {
                '@if': {
                    exists: { '@path': '$.traits.email' },
                    then: { '@path': '$.traits.email' },
                    else: { '@path': '$.context.traits.email' }
                }
            },
            category: 'hashedPII'
        },
        phone: {
            label: 'User Phone',
            description: 'Phone number of a user.',
            type: 'string',
            unsafe_hidden: false,
            required: false,
            default: {
                '@if': {
                    exists: { '@path': '$.traits.phone' },
                    then: { '@path': '$.traits.phone' },
                    else: { '@path': '$.properties.phone' }
                }
            },
            category: 'hashedPII'
        },
        device_type: {
            label: 'User Mobile Device Type',
            description: "User's mobile device type",
            type: 'string',
            unsafe_hidden: false,
            required: false,
            default: {
                '@path': '$.context.device.type'
            }
        },
        advertising_id: {
            label: 'User Mobile Advertising ID',
            description: "User's mobile advertising Id.",
            type: 'string',
            unsafe_hidden: false,
            required: false,
            default: {
                '@path': '$.context.device.advertisingId'
            }
        },
        segment_audience_key: {
            label: 'Segment Audience Key',
            description: 'Segment Audience Key. Maps to the "Name" of the Segment node in Delivr AI Audience Segmentation.',
            type: 'string',
            required: true,
            default: {
                '@path': '$.context.personas.computation_key'
            }
        },
        enable_batching: {
            label: 'Batch Data to Delivr AI',
            description: 'If true, batch requests to Delivr AI. Delivr AI accepts batches of up to 1000 events. If false, send each event individually.',
            type: 'boolean',
            default: true,
            unsafe_hidden: true
        },
        batch_size: {
            label: 'Batch Size',
            description: 'Maximum number of events to include in each batch. Actual batch sizes may be lower.',
            type: 'number',
            default: 1000,
            unsafe_hidden: true
        }
    },
    perform: async (request, { payload, settings }) => {
        let rt_access_token_response;
        try {
            rt_access_token_response = await (0, utils_rt_1.generate_jwt)(settings.client_identifier_id, request);
        }
        catch (error) {
            if (error === 401) {
                throw new actions_core_1.InvalidAuthenticationError('Invalid Client Identifier ID');
            }
            else {
                throw new actions_core_1.APIError('Error Generating JWT', 400);
            }
        }
        const rt_access_token = rt_access_token_response?.data?.token;
        return process_payload(request, [payload], rt_access_token, settings.client_identifier_id);
    },
    performBatch: async (request, { payload, settings }) => {
        let rt_access_token_response;
        try {
            rt_access_token_response = await (0, utils_rt_1.generate_jwt)(settings.client_identifier_id, request);
        }
        catch (error) {
            if (error === 401) {
                throw new actions_core_1.InvalidAuthenticationError('Invalid Client Identifier ID');
            }
            else {
                throw new actions_core_1.APIError('Error Generating JWT', 400);
            }
        }
        const rt_access_token = rt_access_token_response?.data?.token;
        return process_payload(request, payload, rt_access_token, settings.client_identifier_id);
    }
};
async function process_payload(request, payload, token, client_identifier_id) {
    const body = (0, utils_rt_1.gen_update_segment_payload)(payload, client_identifier_id);
    if (body.data.length > 0) {
        return await request(`${constants_1.DELIVRAI_BASE_URL}${constants_1.DELIVRAI_SEGMENTATION_AUDIENCE}`, {
            method: 'POST',
            json: body,
            headers: {
                Authorization: `Bearer ${token}`
            }
        }).catch((err) => {
            throw new actions_core_1.APIError('HTTP error: ' + err?.response?.statusText || 'Something went wrong', err?.response?.status || 500);
        });
    }
    else {
        throw new actions_core_1.PayloadValidationError('Selected identifier(s) not available in the event(s)');
    }
}
exports.default = action;
//# sourceMappingURL=index.js.map