"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.authCreds = void 0;
exports.getAuthCreds = getAuthCreds;
exports.getAccessToken = getAccessToken;
exports.doPOST = doPOST;
const actions_core_1 = require("@segment/actions-core");
exports.authCreds = {
    accessToken: '',
    clientId: '',
    clientSecret: '',
    refreshToken: '',
    refreshTokenUrl: ''
};
function getAuthCreds() {
    return exports.authCreds;
}
async function getAccessToken(request, settings) {
    exports.authCreds = getAuthCreds();
    exports.authCreds.accessToken = '';
    exports.authCreds.clientId = settings.a_clientId;
    exports.authCreds.clientSecret = settings.a_clientSecret;
    exports.authCreds.refreshToken = settings.a_refreshToken;
    exports.authCreds.refreshTokenUrl = `https://api-campaign-${settings.region}-${settings.pod}.goacoustic.com/oauth/token`;
    const requestAToken = await request(exports.authCreds.refreshTokenUrl, {
        method: 'POST',
        body: new URLSearchParams({
            refresh_token: exports.authCreds.refreshToken,
            client_id: exports.authCreds.clientId,
            client_secret: exports.authCreds.clientSecret,
            grant_type: 'refresh_token'
        }),
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'User-Agent': 'Segment Action (Acoustic Destination) "GetAccessToken"'
        }
    });
    const ratResp = (await requestAToken.data);
    exports.authCreds.accessToken = ratResp.access_token;
    return { accessToken: exports.authCreds.accessToken, refreshToken: exports.authCreds.refreshToken };
}
async function doPOST(request, settings, auth, body, action) {
    let resultTxt = '';
    let res = '';
    const postResults = await request(`https://api-campaign-${settings.region}-${settings.pod}.goacoustic.com/XMLAPI`, {
        method: 'POST',
        headers: {
            Authorization: `Bearer ${auth?.accessToken}`,
            'Content-Type': 'text/xml',
            'user-agent': `Segment Action (Acoustic Destination) ${action}`,
            Connection: 'keep-alive',
            'Accept-Encoding': 'gzip, deflate, br',
            Accept: '*/*'
        },
        body: `${body}`
    });
    res = (await postResults.data);
    resultTxt = res;
    if (resultTxt.toLowerCase().indexOf('<success>false</success>') > -1) {
        const rx = /<FaultString>(.*)<\/FaultString>/gm;
        const r = rx.exec(resultTxt);
        const faultMsg = r[1].toLowerCase();
        if (faultMsg.indexOf('max number of concurrent') > -1)
            throw new actions_core_1.RetryableError('Currently exceeding Max number of concurrent API authenticated requests, retrying...', 429);
    }
    return resultTxt;
}
//# sourceMappingURL=tablemaintutilities.js.map