"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleRequestError = void 0;
const actions_core_1 = require("@segment/actions-core");
const isGoogleAPIError = (error) => {
    if (typeof error === 'object' && error !== null) {
        const e = error;
        return (typeof e.response === 'object' &&
            e.response !== null &&
            typeof e.response.data === 'object' &&
            e.response.data !== null &&
            typeof e.response.data.error === 'object' &&
            e.response.data.error !== null);
    }
    return false;
};
const handleRequestError = (error, statsName, statsContext) => {
    const { statsClient, tags: statsTags } = statsContext || {};
    if (!isGoogleAPIError(error)) {
        if (!error) {
            statsTags?.push('error:unknown');
            statsClient?.incr(`${statsName}.error`, 1, statsTags);
            return new actions_core_1.IntegrationError('Unknown error', 'UNKNOWN_ERROR', 500);
        }
    }
    const gError = error;
    const code = gError.response?.status;
    const message = gError.response?.data?.error?.message || gError.response?.data?.[0]?.error?.message;
    if (code === 401) {
        statsTags?.push('error:invalid-authentication');
        statsClient?.incr(`${statsName}.error`, 1, statsTags);
        return new actions_core_1.InvalidAuthenticationError(message, actions_core_1.ErrorCodes.INVALID_AUTHENTICATION);
    }
    if (code === 403) {
        statsTags?.push('error:forbidden');
        statsClient?.incr(`${statsName}.error`, 1, statsTags);
        return new actions_core_1.IntegrationError(message, 'FORBIDDEN', 403);
    }
    if (code === 501) {
        statsTags?.push('error:integration-error');
        statsClient?.incr(`${statsName}.error`, 1, statsTags);
        return new actions_core_1.IntegrationError(message, 'INTEGRATION_ERROR', 501);
    }
    if (code === 408 || code === 423 || code === 429 || code >= 500) {
        statsTags?.push('error:retryable-error');
        statsClient?.incr(`${statsName}.error`, 1, statsTags);
        return new actions_core_1.IntegrationError(message, 'RETRYABLE_ERROR', code);
    }
    statsTags?.push('error:generic-error');
    statsClient?.incr(`${statsName}.error`, 1, statsTags);
    return new actions_core_1.IntegrationError(message, 'INTEGRATION_ERROR', code);
};
exports.handleRequestError = handleRequestError;
//# sourceMappingURL=errors.js.map