"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleHttpError = exports.handleMultistatusResponse = exports.sendDataToMicrosoftBingAds = exports.preparePayload = exports.categorizePayloadByAction = exports.hashEmail = void 0;
const hashing_utils_1 = require("../../lib/hashing-utils");
const actions_core_1 = require("@segment/actions-core");
const constants_1 = require("./constants");
const hashEmail = (item) => {
    return (0, hashing_utils_1.processHashing)(item, 'sha256', 'hex', (value) => value.trim().toLowerCase());
};
exports.hashEmail = hashEmail;
const categorizePayloadByAction = (payload, addMap, removeMap) => {
    payload.forEach((p, index) => {
        const action = p.traits_or_props[p.audience_key] ? 'Add' : 'Remove';
        const identifier = (p.identifier_type === 'Email' ? (0, exports.hashEmail)(p.email) : p.crm_id);
        if (action === 'Add') {
            if (!addMap.has(identifier)) {
                addMap.set(identifier, []);
            }
            addMap.get(identifier)?.push(index);
        }
        else {
            if (!removeMap.has(identifier)) {
                removeMap.set(identifier, []);
            }
            removeMap.get(identifier)?.push(index);
        }
    });
};
exports.categorizePayloadByAction = categorizePayloadByAction;
const preparePayload = (audienceId, action, identifierType, listItems) => {
    return {
        CustomerListUserData: {
            ActionType: action,
            AudienceId: audienceId,
            CustomerListItemSubType: identifierType,
            CustomerListItems: listItems
        }
    };
};
exports.preparePayload = preparePayload;
const sendDataToMicrosoftBingAds = async (request, payload) => {
    const response = await request(`${constants_1.BASE_URL}/CustomerListUserData/Apply`, {
        method: 'POST',
        json: payload
    });
    return response;
};
exports.sendDataToMicrosoftBingAds = sendDataToMicrosoftBingAds;
const handleMultistatusResponse = (msResponse, response, items, listItemsMap, payload, isBatch) => {
    const responseData = response?.data;
    if (responseData?.PartialErrors && responseData.PartialErrors.length > 0) {
        if (!isBatch) {
            throw new actions_core_1.IntegrationError(responseData.PartialErrors[0].Message, 'PartialErrors', 400);
        }
        responseData.PartialErrors.forEach((error) => {
            if (typeof error.Index === 'number' && error.Index >= 0 && error.Index < items.length) {
                const item = items[error.Index];
                const originalIndices = listItemsMap.get(item);
                if (originalIndices !== undefined && originalIndices.length > 0) {
                    originalIndices.forEach((originalIndex) => {
                        msResponse.setErrorResponseAtIndex(originalIndex, {
                            status: error.Code || 400,
                            errormessage: `${error.ErrorCode ?? 'UnknownError'}: ${error.Message ?? 'No error message provided'}`,
                            sent: payload[originalIndex],
                            body: JSON.stringify(error)
                        });
                    });
                    listItemsMap.delete(item);
                }
            }
        });
    }
    listItemsMap.forEach((indices) => {
        indices.forEach((index) => {
            msResponse.setSuccessResponseAtIndex(index, {
                status: 200,
                sent: payload[index],
                body: JSON.stringify(response) || 'Success'
            });
        });
    });
};
exports.handleMultistatusResponse = handleMultistatusResponse;
const handleHttpError = async (msResponse, error, listItemsMap, payload) => {
    const errorResponse = await error?.response?.json();
    listItemsMap.forEach((indices) => {
        indices.forEach((index) => {
            msResponse.setErrorResponseAtIndex(index, {
                status: errorResponse?.status,
                errormessage: errorResponse?.message || error.message,
                sent: payload[index],
                body: JSON.stringify(errorResponse)
            });
        });
    });
};
exports.handleHttpError = handleHttpError;
//# sourceMappingURL=utils.js.map