import * as sidecar from '@@/sidecar-registry';

// The officer-vault sidecar starts its Vaultwarden reverse-proxy on a random loopback port and reports it
// here on connect. We remember it so `/api/vault/*` (HTTP) and the notifications WebSocket always forward
// to the current sidecar. The platform holds NO knowledge of Vaultwarden itself — only where the sidecar is.

let serverPort: number | null = null;

sidecar.on('vault:server', (msg) => {
  const port = (msg as { port?: number }).port;
  if (typeof port !== 'number') return;
  serverPort = port;
  console.log(`[vault] sidecar proxy registered on port ${port}`);
});

/** Base URL of the sidecar's HTTP proxy, or null if the sidecar hasn't reported in yet. */
export function getVaultServerUrl(): string | null {
  return serverPort ? `http://127.0.0.1:${serverPort}` : null;
}

/** Same, as a WebSocket base for the notifications hub. */
export function getVaultServerWsUrl(): string | null {
  return serverPort ? `ws://127.0.0.1:${serverPort}` : null;
}
