/**
 * Server startup hook. Next.js calls register() once per Node process
 * when the server boots (App Router convention).
 *
 * We use this to install undici's ProxyAgent as the global dispatcher
 * so the in-cluster web-proxy (Squid at web-proxy.web-proxy.svc:3128)
 * is honored by Node's built-in `fetch()`. Without this, fetch() goes
 * direct → Calico default-deny-external drops outbound TCP → NextAuth
 * issuer discovery times out → /api/auth/error?error=Configuration.
 *
 * HTTP_PROXY / HTTPS_PROXY / NO_PROXY env vars are read by EnvHttpProxyAgent.
 * If neither is set (e.g., local `next dev`), no proxy is configured.
 */
export async function register() {
  if (process.env.NEXT_RUNTIME !== "nodejs") return;
  if (!process.env.HTTPS_PROXY && !process.env.HTTP_PROXY) return;

  const { setGlobalDispatcher, EnvHttpProxyAgent } = await import("undici");
  setGlobalDispatcher(new EnvHttpProxyAgent());
  // eslint-disable-next-line no-console
  console.log(
    `[instrumentation] undici proxy via ${process.env.HTTPS_PROXY ?? process.env.HTTP_PROXY}`,
  );
}
