"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validate = validate;
exports.send = send;
const actions_core_1 = require("@segment/actions-core");
function validate(payloads) {
    for (const payload of payloads) {
        if (!payload.target || Object.keys(payload.target).length === 0) {
            throw new actions_core_1.PayloadValidationError('At least one target identifier is required.');
        }
    }
    return payloads;
}
async function send(request, payloads, settings, isBatch) {
    if (!isBatch) {
        validate(payloads);
    }
    const json = payloads.map((payload) => buildEventJSON(payload));
    const response = await request(`${settings.integrationURL}/subscriber`, {
        method: 'POST',
        json,
        headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${settings.apiKey}`
        }
    });
    if (isBatch) {
        const multiStatusResponse = new actions_core_1.MultiStatusResponse();
        response.data.forEach((res, index) => {
            if (res.code >= 200 && res.code < 300) {
                multiStatusResponse.setSuccessResponseAtIndex(index, {
                    status: res.code,
                    sent: json[index],
                    body: res
                });
            }
            else {
                multiStatusResponse.setErrorResponseAtIndex(index, {
                    status: res.code,
                    sent: json[index],
                    body: res,
                    errormessage: res.description
                });
            }
        });
        return multiStatusResponse;
    }
    return response;
}
function buildEventJSON(payload) {
    const { products, eventData } = payload;
    const data = { ...eventData, products };
    const eventItem = {
        event: {
            target: payload.target,
            data,
            type: payload.eventType
        }
    };
    return eventItem;
}
//# sourceMappingURL=utils.js.map