// slskd upstream config + header hygiene for the officer-slskd sidecar.
//
// All knowledge of the slskd instance (its URL and API key) lives in the sidecar, mirroring the
// officer-vault philosophy: the platform API is a thin auth+forward proxy and holds NO slskd
// credentials. The sidecar injects the API key on every forwarded request; the platform never sees it.

const { SLSKD_URL, SLSKD_API_KEY } = process.env;

let warnedUnset = false;

/** The slskd base URL (no trailing slash), or null when unconfigured (the sidecar then 503s). */
export function getSlskdBase(): string | null {
  const raw = SLSKD_URL?.trim();
  if (!raw) {
    if (!warnedUnset) {
      console.warn('[slskd] SLSKD_URL is unset — the sidecar will respond 503 until it is set');
      warnedUnset = true;
    }
    return null;
  }
  return raw.replace(/\/+$/, '');
}

/** The slskd API key, injected as `X-API-Key` on every forwarded request. Null when unconfigured. */
export function getSlskdApiKey(): string | null {
  const raw = SLSKD_API_KEY?.trim();
  return raw ? raw : null;
}

// Hop-by-hop headers must not cross a proxy hop (RFC 7230 §6.1). `host` is dropped so the outgoing
// fetch sets the upstream authority itself; everything else — including our injected X-API-Key — passes.
const HOP_BY_HOP = new Set([
  'connection',
  'keep-alive',
  'proxy-authenticate',
  'proxy-authorization',
  'te',
  'trailer',
  'transfer-encoding',
  'upgrade',
  'host',
]);

/** Copy headers, dropping only hop-by-hop / proxy-* ones. Used for both request and response directions. */
export function stripHopByHop(src: Headers): Headers {
  const out = new Headers();
  src.forEach((value, key) => {
    const k = key.toLowerCase();
    if (HOP_BY_HOP.has(k) || k.startsWith('proxy-')) return;
    out.set(key, value);
  });
  return out;
}
