/**
 * Preconnect to the API to overlap TCP+TLS handshake with startup.
 *
 * Kicks a fire-and-forget HEAD against the configured base URL so the
 * connection is warmed in the global keep-alive pool before the first real
 * request. Skipped when proxy/mTLS/unix-socket transports are configured,
 * since those would bypass the shared pool.
 */

import { isEnvTruthy } from './envUtils.js'

let fired = false

export function preconnectApi(): void {
  if (fired) return
  fired = true

  if (
    isEnvTruthy(process.env.SANDCODE_USE_BEDROCK) ||
    isEnvTruthy(process.env.SANDCODE_USE_VERTEX) ||
    isEnvTruthy(process.env.SANDCODE_USE_FOUNDRY)
  ) {
    return
  }

  if (
    process.env.HTTPS_PROXY ||
    process.env.https_proxy ||
    process.env.HTTP_PROXY ||
    process.env.http_proxy ||
    process.env.SANDCODE_UNIX_SOCKET ||
    process.env.SANDCODE_CLIENT_CERT ||
    process.env.SANDCODE_CLIENT_KEY
  ) {
    return
  }

  const baseUrl = process.env.SANDCODE_BASE_URL
  if (!baseUrl) return

  // eslint-disable-next-line eslint-plugin-n/no-unsupported-features/node-builtins
  void fetch(baseUrl, {
    method: 'HEAD',
    signal: AbortSignal.timeout(10_000),
  }).catch(() => {})
}
