// Standalone replica of accountRoutes.proxyToBackend, to figure out
// why the in-process call fails while my curl/node-fetch from the
// same machine succeed. Run with: node scripts/debug-balance-probe.mjs
import { readFileSync } from 'fs';

const cfg = JSON.parse(readFileSync('config/default.json', 'utf8'));
const baseUrl = (cfg.backend?.baseUrl || 'https://autopilot-api.azurewebsites.net').replace(/\/$/, '');

// Pull JWT from the running server (same path /api/auth/status uses).
const jwt = await (await fetch('http://localhost:8080/api/auth/status')).json().then(d => d.jwt);
console.log('Using JWT len:', jwt?.length, 'against baseUrl:', baseUrl);
console.log();

async function proxyLike(path) {
  const url = `${baseUrl}${path}`;
  const t0 = Date.now();
  try {
    const res = await fetch(url, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${jwt}`,
        'Content-Type': 'application/json',
      },
    });
    const text = await res.text();
    let parsed; try { parsed = JSON.parse(text); } catch { parsed = { raw: text.slice(0, 200) }; }
    console.log(`${path}: status=${res.status} ms=${Date.now() - t0} body=${JSON.stringify(parsed).slice(0, 200)}`);
  } catch (err) {
    console.log(`${path}: ERR ${err.message}`);
  }
}

for (const p of ['/subscription/status', '/account/profile', '/auth/me', '/auth/apikeys']) {
  await proxyLike(p);
}
