"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getEndpointByRegion = getEndpointByRegion;
exports.createAudience = createAudience;
exports.getAudience = getAudience;
const actions_core_1 = require("@segment/actions-core");
const constants_1 = require("./constants");
function getEndpointByRegion(endpoint, region) {
    return constants_1.endpoints[endpoint][region] ?? constants_1.endpoints[endpoint]['north_america'];
}
async function createAudience(request, settings, name, id_type, owner_email) {
    const { endpoint, app_id, default_owner_email } = settings;
    if (!name) {
        throw new actions_core_1.IntegrationError('Missing audience name value', 'MISSING_REQUIRED_FIELD', 400);
    }
    if (!id_type) {
        throw new actions_core_1.IntegrationError('Missing id_type value', 'MISSING_REQUIRED_FIELD', 400);
    }
    const url = getEndpointByRegion('cohorts_upload', endpoint);
    const json = {
        name,
        app_id,
        id_type,
        ids: [],
        owner: owner_email ?? default_owner_email,
        published: true
    };
    const response = await request(url, {
        method: 'post',
        json
    });
    const id = response?.data?.cohortId;
    if (!id) {
        throw new actions_core_1.IntegrationError('Invalid response from Amplitude Cohorts API when attempting to create new Cohort: Missing cohortId', 'INVALID_RESPONSE', 500);
    }
    return id;
}
async function getAudience(request, settings, externalId) {
    const { endpoint } = settings;
    const url = `${getEndpointByRegion('cohorts_get_one', endpoint)}/${externalId}`;
    const response = await request(url);
    const id = response?.data?.cohortId;
    if (!id) {
        throw new actions_core_1.IntegrationError('Invalid response from Amplitude Cohorts API when attempting to get Cohort: Missing cohortId', 'INVALID_RESPONSE', 500);
    }
    if (id !== externalId) {
        throw new actions_core_1.IntegrationError(`Cohort with id ${externalId} not found`, 'COHORT_NOT_FOUND', 404);
    }
}
//# sourceMappingURL=functions.js.map