import type { AxiosRequestConfig } from 'axios';

const proxyEnvNames = [
    'HTTPS_PROXY',
    'https_proxy',
    'HTTP_PROXY',
    'http_proxy',
    'ALL_PROXY',
    'all_proxy',
    'npm_config_https_proxy',
    'npm_config_proxy',
];

function getUnsupportedProxyEnv(): { name: string; value: string } | null {
    for (const name of proxyEnvNames) {
        const value = (process.env[name] || '').trim();
        if (!value) continue;

        try {
            const protocol = new URL(value).protocol.toLowerCase();
            if (protocol.startsWith('socks')) {
                return { name, value };
            }
        } catch {
            if (/^socks/i.test(value)) {
                return { name, value };
            }
        }
    }

    return null;
}

export function withoutUnsupportedProxy<T extends AxiosRequestConfig>(config: T): T {
    if (Object.prototype.hasOwnProperty.call(config, 'proxy')) {
        return config;
    }

    const unsupportedProxy = getUnsupportedProxyEnv();
    if (!unsupportedProxy) {
        return config;
    }

    return {
        ...config,
        proxy: false,
    } as T;
}
