import { expect, test } from "bun:test";
import {
  CONNECTION_IDLE_TIMEOUT_MS,
  RECONNECT_MAX_DELAY_MS,
  getReconnectDelayMs,
  isConnectionStale,
  isTerminalSocketClose,
} from "./connection";

test("getReconnectDelayMs grows with backoff and caps at the max delay", () => {
  expect(getReconnectDelayMs(0, () => 0)).toBe(800);
  expect(getReconnectDelayMs(1, () => 0)).toBe(1600);
  expect(getReconnectDelayMs(4, () => 0)).toBe(8000);
  expect(getReconnectDelayMs(8, () => 1)).toBe(Math.round(RECONNECT_MAX_DELAY_MS * 1.2));
});

test("isConnectionStale respects the idle timeout", () => {
  const now = 100_000;
  expect(isConnectionStale(now - CONNECTION_IDLE_TIMEOUT_MS + 1, now)).toBe(false);
  expect(isConnectionStale(now - CONNECTION_IDLE_TIMEOUT_MS - 1, now)).toBe(true);
  expect(isConnectionStale(null, now)).toBe(false);
});

test("isTerminalSocketClose only resets on invalid session/player closes", () => {
  expect(isTerminalSocketClose(1008, "Session not found")).toBe(true);
  expect(isTerminalSocketClose(1008, "Player not found")).toBe(true);
  expect(isTerminalSocketClose(4000, "Connection stale")).toBe(false);
  expect(isTerminalSocketClose(1008, "Policy violation")).toBe(false);
});
