import { ProxyAgent, fetch } from 'undici';
import axios from 'axios';
import { HttpsProxyAgent } from 'https-proxy-agent';

async function main() {
  const proxy = new URL(process.env.QUOTAGUARDSTATIC_URL);
  const target = new URL(process.env.QG_TARGET_URL);
  const token = process.env.DESTINATION_API_TOKEN || '';
  if (!['http:', 'https:'].includes(proxy.protocol) || !proxy.username || !proxy.password ||
      target.protocol !== 'https:' || target.username || target.password ||
      /[\x00-\x1f\x7f]/.test(token) || (token && target.hostname === 'ip.quotaguard.com')) {
    throw new Error('Invalid configuration');
  }
  const headers = token ? { Authorization: `Bearer ${token}` } : {};
  const mode = process.argv[2] || 'fetch';
  if (mode === 'fetch') {
    const dispatcher = new ProxyAgent(proxy.href);
    try {
      const response = await fetch(target, { dispatcher, headers, redirect: 'manual',
        signal: AbortSignal.timeout(30000) });
      await response.body?.cancel();
      if (!response.ok) throw new Error('Status');
    } finally { await dispatcher.close(); }
  } else if (mode === 'axios') {
    const agent = new HttpsProxyAgent(proxy.href);
    try {
      await axios.get(target.href, { httpsAgent: agent, proxy: false, headers,
        maxRedirects: 0, timeout: 30000, responseType: 'stream' }).then(response => {
          response.data.destroy();
          if (response.status < 200 || response.status >= 300) throw new Error('Status');
        });
    } finally { agent.destroy(); }
  } else { throw new Error('Choose fetch or axios'); }
  console.log('PASS: destination returned a successful HTTP status');
}
main().catch(() => { console.error('Request failed; check configuration and the guide.'); process.exitCode = 1; });
