"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) {
    if (payloads.length === 1) {
        const p = payloads[0];
        if (!p.identifiers || Object.keys(p.identifiers).length === 0) {
            throw new actions_core_1.PayloadValidationError('At least one identifier is required.');
        }
    }
    return payloads;
}
async function send(request, payloads, settings, isBatch) {
    if (!isBatch) {
        validate(payloads);
    }
    const json = payloads.map((payload) => buildJSON(payload, settings.organizationId));
    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 buildJSON(payload, organizationId) {
    const { identifiers, traits: { title, firstname, lastname, dob, address, address2, address3, suburb, state, country, postcode, phone, gender, ...customTraits } = {} } = payload;
    const json = {
        profile: {
            organizationId: Number(organizationId),
            ...identifiers,
            ...(title && { title }),
            ...(firstname && { firstname }),
            ...(lastname && { lastname }),
            ...(dob && { dob }),
            ...(address && { address }),
            ...(address2 && { address2 }),
            ...(address3 && { address3 }),
            ...(suburb && { suburb }),
            ...(state && { state }),
            ...(country && { country }),
            ...(postcode && { postcode }),
            ...(phone && { phone }),
            ...(gender && { gender }),
            ...buildCustom(customTraits),
            ...buildLists(payload)
        }
    };
    return json;
}
function buildCustom(customTraits) {
    if (customTraits && Object.keys(customTraits).length > 0) {
        return {
            custom: customTraits
        };
    }
    return {};
}
function buildLists(payload) {
    const lists = [];
    if (payload.subscribeLists && payload.subscribeLists.length > 0) {
        lists.push(...payload.subscribeLists.map((list) => ({
            listId: Number(list),
            unsubscribedTimestamp: null
        })));
    }
    if (payload.unsubscribeLists && payload.unsubscribeLists.length > 0) {
        lists.push(...payload.unsubscribeLists.map((list) => ({
            listId: Number(list),
            unsubscribedTimestamp: payload.timestamp
        })));
    }
    return lists.length > 0 ? { lists } : {};
}
//# sourceMappingURL=utils.js.map