"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.UK_EEA_COUNTRY_CODES = exports.COUNTRY_CODES = exports.FLAG_CONSENT_ENABLE_ERRORS = exports.FLAG_CONSENT_REQUIRED = 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.FLAG_CONSENT_REQUIRED = 'actions-amazon-amc-consent';
exports.FLAG_CONSENT_ENABLE_ERRORS = 'actions-amazon-amc-consent-enable-errors';
exports.COUNTRY_CODES = [
    "AD", "AE", "AF", "AG", "AI", "AL", "AM", "AO", "AQ", "AR", "AS", "AT", "AU", "AW", "AX", "AZ",
    "BA", "BB", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BL", "BM", "BN", "BO", "BQ", "BR", "BS",
    "BT", "BV", "BW", "BY", "BZ", "CA", "CC", "CD", "CF", "CG", "CH", "CI", "CK", "CL", "CM", "CN",
    "CO", "CR", "CU", "CV", "CW", "CX", "CY", "CZ", "DE", "DJ", "DK", "DM", "DO", "DZ", "EC", "EE",
    "EG", "EH", "ER", "ES", "ET", "FI", "FJ", "FK", "FM", "FO", "FR", "GA", "GB", "GD", "GE", "GF",
    "GG", "GH", "GI", "GL", "GM", "GN", "GP", "GQ", "GR", "GS", "GT", "GU", "GW", "GY", "HK", "HM",
    "HN", "HR", "HT", "HU", "ID", "IE", "IL", "IM", "IN", "IO", "IQ", "IR", "IS", "IT", "JE", "JM",
    "JO", "JP", "KE", "KG", "KH", "KI", "KM", "KN", "KP", "KR", "KW", "KY", "KZ", "LA", "LB", "LC",
    "LI", "LK", "LR", "LS", "LT", "LU", "LV", "LY", "MA", "MC", "MD", "ME", "MF", "MG", "MH", "MK",
    "ML", "MM", "MN", "MO", "MP", "MQ", "MR", "MS", "MT", "MU", "MV", "MW", "MX", "MY", "MZ", "NA",
    "NC", "NE", "NF", "NG", "NI", "NL", "NO", "NP", "NR", "NU", "NZ", "OM", "PA", "PE", "PF", "PG",
    "PH", "PK", "PL", "PM", "PN", "PR", "PS", "PT", "PW", "PY", "QA", "RE", "RO", "RS", "RU", "RW",
    "SA", "SB", "SC", "SD", "SE", "SG", "SH", "SI", "SJ", "SK", "SL", "SM", "SN", "SO", "SR", "SS",
    "ST", "SV", "SX", "SY", "SZ", "TC", "TD", "TF", "TG", "TH", "TJ", "TK", "TL", "TM", "TN", "TO",
    "TR", "TT", "TV", "TW", "TZ", "UA", "UG", "UM", "US", "UY", "UZ", "VA", "VC", "VE", "VG", "VI",
    "VN", "VU", "WF", "WS", "YE", "YT", "ZA", "ZM", "ZW"
];
exports.UK_EEA_COUNTRY_CODES = [
    "GB", "AT", "BE", "BG", "HR", "CY", "CZ", "DK", "EE", "FI", "FR", "DE", "GR", "HU", "IE", "IT",
    "LV", "LT", "LU", "MT", "NL", "PL", "PT", "RO", "SK", "SI", "ES", "SE", "IS", "LI", "NO", "CH"
];
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