"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.send = send;
const actions_core_1 = require("@segment/actions-core");
const actions_shared_1 = require("@segment/actions-shared");
async function send(request, payload, settings) {
    const { computation_key, external_audience_id, emailIdentifier, mobileNumberIdentifier, traits_or_props, dataFields } = payload;
    const { api_host } = settings;
    const action = typeof traits_or_props[computation_key] == 'boolean' ? traits_or_props[computation_key] : undefined;
    if (action === undefined) {
        throw new actions_core_1.PayloadValidationError(`Audience with computation_key = ${computation_key} is missing information about whether to add or remove the contact from the Audience.`);
    }
    const identifier = emailIdentifier ? 'email' : mobileNumberIdentifier ? 'mobileNumber' : null;
    const value = emailIdentifier ?? mobileNumberIdentifier ?? null;
    if (!identifier || !value) {
        throw new actions_core_1.PayloadValidationError('At least one identifier (email or mobile number) must be provided.');
    }
    const numericAudienceId = Number(external_audience_id);
    if (isNaN(numericAudienceId)) {
        throw new actions_core_1.PayloadValidationError('external_audience_id must be a numeric value.');
    }
    const url = `${settings.api_host}/contacts/v3/${identifier}/${value}`;
    const identifiers = {
        ...(emailIdentifier && { email: emailIdentifier }),
        ...(mobileNumberIdentifier && { mobileNumber: mobileNumberIdentifier })
    };
    const channelProperties = {
        ...(emailIdentifier && {
            email: {
                status: 'subscribed',
                emailType: 'html',
                optInType: 'single'
            }
        }),
        ...(mobileNumberIdentifier && {
            sms: { status: 'subscribed' }
        })
    };
    const fieldsAPI = new actions_shared_1.DDDataFieldsApi(api_host, request);
    const validDataFields = await fieldsAPI.validateDataFields({ dataFields });
    const json = {
        identifiers,
        channelProperties,
        lists: [numericAudienceId],
        ...(validDataFields && { dataFields: validDataFields })
    };
    return request(url, {
        method: action ? 'PATCH' : 'DELETE',
        ...(action ? { json } : {})
    });
}
//# sourceMappingURL=functions.js.map