"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TTL_MAX_VALUE = exports.REGEX_EXTERNALUSERID = exports.getAuthSettings = exports.getAuthToken = exports.REGEX_ADVERTISERID = exports.REGEX_AUDIENCEID = exports.CURRENCY = exports.CONSTANTS = exports.AUTHORIZATION_URL = exports.AmazonAdsError = void 0;
exports.extractNumberAndSubstituteWithStringValue = extractNumberAndSubstituteWithStringValue;
const actions_core_1 = require("@segment/actions-core");
class AmazonAdsError extends actions_core_1.HTTPError {
}
exports.AmazonAdsError = AmazonAdsError;
exports.AUTHORIZATION_URL = {
    'https://advertising-api.amazon.com': 'https://api.amazon.com',
    'https://advertising-api-eu.amazon.com': 'https://api.amazon.co.uk',
    'https://advertising-api-fe.amazon.com': 'https://api.amazon.co.jp'
};
exports.CONSTANTS = {
    CREATE: 'CREATE',
    DELETE: 'DELETE'
};
exports.CURRENCY = ['USD', 'CAD', 'JPY', 'GBP', 'EUR', 'SAR', 'AUD', 'AED', 'CNY', 'MXN', 'INR', 'SEK', 'TRY'];
exports.REGEX_AUDIENCEID = /"audienceId":(\d+)/;
exports.REGEX_ADVERTISERID = /"advertiserId":"(\d+)"/;
function extractNumberAndSubstituteWithStringValue(responseString, regex, substituteWith) {
    const resString = responseString.replace(regex, substituteWith);
    return JSON.parse(resString);
}
const getAuthToken = async (request, settings, auth) => {
    const endpoint = exports.AUTHORIZATION_URL[`${settings.region}`];
    try {
        const { data } = await request(`${endpoint}/auth/o2/token`, {
            method: 'POST',
            body: new URLSearchParams({
                refresh_token: auth.refreshToken,
                client_id: auth.clientId,
                client_secret: auth.clientSecret,
                grant_type: 'refresh_token'
            }),
            headers: {
                authorization: ''
            },
            timeout: 15000
        });
        return data.access_token;
    }
    catch (e) {
        const error = e;
        if (error.response?.data?.error === 'invalid_grant') {
            throw new actions_core_1.InvalidAuthenticationError(`Invalid Authentication: Your refresh token is invalid or expired. Please re-authenticate to fetch a new refresh token.`, actions_core_1.ErrorCodes.REFRESH_TOKEN_EXPIRED);
        }
        throw new actions_core_1.InvalidAuthenticationError(`Failed to fetch a new access token. Reason: ${error.response?.data?.error}`, actions_core_1.ErrorCodes.OAUTH_REFRESH_FAILED);
    }
};
exports.getAuthToken = getAuthToken;
const getAuthSettings = (settings) => {
    return {
        refreshToken: settings.oauth?.refresh_token,
        accessToken: settings.oauth?.access_token,
        clientId: process.env.ACTIONS_AMAZON_AMC_CLIENT_ID,
        clientSecret: process.env.ACTIONS_AMAZON_AMC_CLIENT_SECRET
    };
};
exports.getAuthSettings = getAuthSettings;
exports.REGEX_EXTERNALUSERID = /^[0-9a-zA-Z-_]{1,128}$/;
exports.TTL_MAX_VALUE = 34300800;
//# sourceMappingURL=utils.js.map