export const sshProxySendDrainTimeoutMs = 60_000;

export type SshProxyQueuedMessage = string | Buffer;

export function flushWebSocketSendQueue(
  queue: SshProxyQueuedMessage[],
  send: (message: SshProxyQueuedMessage) => number,
): { backpressured: boolean; dropped: boolean } {
  while (queue.length > 0) {
    const status = send(queue[0]!);
    if (status === 0) return { backpressured: true, dropped: true };
    queue.shift();
    if (status === -1) return { backpressured: true, dropped: false };
  }
  return { backpressured: false, dropped: false };
}

export async function waitForWebSocketSendDrain(
  bufferedAmount: () => number,
  options: { timeoutMs?: number | null; pollMs?: number } = {},
): Promise<void> {
  const timeoutMs = options.timeoutMs ?? sshProxySendDrainTimeoutMs;
  const pollMs = options.pollMs ?? 5;
  const deadline = options.timeoutMs === null ? Number.POSITIVE_INFINITY : Date.now() + timeoutMs;
  while (bufferedAmount() > 0 && Date.now() < deadline) {
    await new Promise<void>((resolve) => setTimeout(resolve, pollMs));
  }
}
