"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const actions_core_1 = require("@segment/actions-core");
const fields_1 = require("./fields");
const constants_1 = require("./constants");
const hashing_utils_1 = require("../../../lib/hashing-utils");
const action = {
    title: 'Send CAPI Event',
    description: 'Send a track or page event to Microsoft Bing CAPI.',
    defaultSubscription: 'type = "track" or type = "page"',
    fields: {
        data: fields_1.data,
        userData: fields_1.userData,
        customData: fields_1.customData,
        items: fields_1.items,
        hotelData: fields_1.hotelData,
        timestamp: fields_1.timestamp,
        enable_batching: fields_1.enable_batching,
        batch_size: fields_1.batch_size
    },
    perform: async (request, { payload, settings }) => {
        return await send(request, [payload], settings, false);
    },
    performBatch: async (request, { payload, settings }) => {
        return await send(request, payload, settings, true);
    }
};
async function send(request, payloads, settings, isBatch) {
    const json = [];
    const multiStatusResponse = new actions_core_1.MultiStatusResponse();
    payloads.forEach((payload) => {
        const { timestamp, data: { eventTime, eventType, adStorageConsent, eventSourceUrl } = {}, userData: { em, ph, ...restOfUserData } = {}, customData, items, hotelData } = payload;
        const jsonItem = {
            ...fields_1.data,
            eventType: eventType,
            eventTime: Math.floor(new Date(eventTime ?? timestamp).getTime() / 1000),
            adStorageConsent: adStorageConsent ?? settings.adStorageConsent,
            eventSourceUrl: eventSourceUrl,
            userData: {
                ...restOfUserData,
                em: em ? (0, hashing_utils_1.processHashing)(em, 'sha256', 'hex', (v) => v.trim().toLowerCase()) : null,
                ph: ph ? (0, hashing_utils_1.processHashing)(ph, 'sha256', 'hex', (v) => v.trim().replace(/\D/g, '')) : null
            },
            customData: customData && {
                ...customData,
                hotelData,
                items: items ?? []
            },
            continueOnValidationError: true
        };
        json.push(jsonItem);
    });
    const response = await request(`${constants_1.API_URL}${settings.UetTag}/events`, {
        method: 'post',
        json: {
            data: json
        }
    });
    const details = response.data?.error?.details ?? [];
    payloads.forEach((payload, index) => {
        const error = details.find((detail) => detail.index === index);
        if (error) {
            multiStatusResponse.setErrorResponseAtIndex(index, {
                status: 400,
                errormessage: error.errorMessage,
                sent: payload,
                body: String(json[index])
            });
        }
        else {
            multiStatusResponse.setSuccessResponseAtIndex(index, {
                status: 200,
                sent: payload,
                body: String(json[index])
            });
        }
    });
    return isBatch ? multiStatusResponse : response;
}
exports.default = action;
//# sourceMappingURL=index.js.map