"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.gen_customer_taxonomy_payload = gen_customer_taxonomy_payload;
exports.gen_segment_subtaxonomy_payload = gen_segment_subtaxonomy_payload;
exports.gen_random_id = gen_random_id;
exports.get_taxonomy_access_token = get_taxonomy_access_token;
exports.update_taxonomy = update_taxonomy;
const actions_core_1 = require("@segment/actions-core");
const utils_rt_1 = require("./utils-rt");
const versioning_info_1 = require("./versioning-info");
const TAXONOMY_CLIENT_KEY_PREFIX = 'idb2b.dsp.datax';
const TAXONOMY_TOKEN_ENDPOINT = `https://id.b2b.yahooincapis.com/zts/${versioning_info_1.YAHOO_AUDIENCES_TAXONOMY_API_VERSION}/oauth2/token`;
const TAXONOMY_AUDIENCE_URL = `https://id.b2b.yahooincapis.com/zts/${versioning_info_1.YAHOO_AUDIENCES_TAXONOMY_API_VERSION}`;
const TAXONOMY_SCOPE = 'idb2b.dsp.datax:role.online.writer';
function gen_customer_taxonomy_payload(settings) {
    const data = {
        id: settings.engage_space_id,
        name: settings.engage_space_id,
        description: settings.customer_desc,
        users: {
            include: [settings.mdm_id]
        }
    };
    const req_body_form = `--SEGMENT-DATA\r\nContent-Disposition: form-data; name="metadata"\r\nContent-Type: application/json;charset=UTF-8\r\n\r\n{ "description" : "${settings.customer_desc}" }\r\n--SEGMENT-DATA\r\nContent-Disposition: form-data; name="data"\r\nContent-Type: application/json;charset=UTF-8\r\n\r\n${JSON.stringify(data)}\r\n--SEGMENT-DATA--`;
    return req_body_form;
}
function gen_segment_subtaxonomy_payload(payload) {
    const data = {
        id: payload.segment_audience_id,
        name: payload.segment_audience_key,
        type: 'SEGMENT'
    };
    const req_body_form = `--SEGMENT-DATA\r\nContent-Disposition: form-data; name="metadata"\r\nContent-Type: application/json;charset=UTF-8\r\n\r\n{ "description" : "Create segment ${data.id}" }\r\n--SEGMENT-DATA\r\nContent-Disposition: form-data; name="data"\r\nContent-Type: application/json;charset=UTF-8\r\n\r\n${JSON.stringify(data)}\r\n--SEGMENT-DATA--`;
    return req_body_form;
}
function gen_random_id(length) {
    const pattern = 'abcdefghijklmnopqrstuvwxyz123456789';
    const random_id = [];
    for (let i = 0; i < length; i++) {
        random_id.push(pattern[Math.floor(Math.random() * pattern.length)]);
    }
    return random_id.join('');
}
async function get_taxonomy_access_token(request, tx_client_key, tx_client_secret) {
    const prefixed_client_key = `${TAXONOMY_CLIENT_KEY_PREFIX}.${tx_client_key}`;
    const jwt = (0, utils_rt_1.generate_jwt)(prefixed_client_key, tx_client_secret);
    const res = await request(TAXONOMY_TOKEN_ENDPOINT, {
        method: 'POST',
        body: new URLSearchParams({
            client_assertion: jwt,
            client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
            grant_type: 'client_credentials',
            scope: TAXONOMY_SCOPE,
            aud: TAXONOMY_AUDIENCE_URL
        })
    });
    if (!res?.data?.access_token) {
        throw new actions_core_1.IntegrationError('Failed to obtain taxonomy access token - missing access_token in response', 'YAHOO_TAXONOMY_TOKEN_ERROR', 500);
    }
    return res.data.access_token;
}
async function update_taxonomy(engage_space_id, tx_creds, request, body_form_data, statsClient, statsTags) {
    const tx_client_secret = tx_creds.tx_client_secret;
    const tx_client_key = tx_creds.tx_client_key;
    const url = `https://datax.yahooapis.com/${versioning_info_1.YAHOO_AUDIENCES_TAXONOMY_API_VERSION}/taxonomy/append${engage_space_id.length > 0 ? '/' + engage_space_id : ''}`;
    const access_token = await get_taxonomy_access_token(request, tx_client_key, tx_client_secret);
    try {
        const add_segment_node = await request(url, {
            method: 'PUT',
            body: body_form_data,
            headers: {
                Authorization: `Bearer ${access_token}`,
                'Content-Type': 'multipart/form-data; boundary=SEGMENT-DATA'
            }
        });
        if (statsClient && statsTags) {
            statsClient.incr('update_taxonomy.success', 1, statsTags);
        }
        return await add_segment_node.json();
    }
    catch (error) {
        const _error = error;
        if (statsClient && statsTags) {
            statsClient.incr('update_taxonomy.error', 1, statsTags);
        }
        if (parseInt(_error.response.status) == 401) {
            throw new actions_core_1.IntegrationError(`Error while updating taxonomy: ${JSON.stringify(_error.response.data)} ${_error.response.status}. Validate Yahoo credentials`, 'YAHOO_TAXONOMY_API_AUTH_ERR', 400);
        }
        else {
            throw error;
        }
    }
}
//# sourceMappingURL=utils-tax.js.map