import type { GatewaySocket, Logger } from "../src/modules/trapos-cloud-gateway/registry.js";

export class FakeSocket implements GatewaySocket {
  readonly sent: string[] = [];
  closed = false;
  closeCode?: number;

  send(data: string): void {
    this.sent.push(data);
  }

  close(code?: number): void {
    this.closed = true;
    this.closeCode = code;
  }

  frames(): Record<string, unknown>[] {
    return this.sent.map((s) => JSON.parse(s) as Record<string, unknown>);
  }

  lastFrame(): Record<string, unknown> {
    if (this.sent.length === 0) {
      throw new Error("no frames sent");
    }
    return JSON.parse(this.sent[this.sent.length - 1]) as Record<string, unknown>;
  }
}

// Silent logger for unit tests (and a capturing variant when a test wants to assert
// on drop reasons).
export const silentLog: Logger = {
  debug: () => undefined,
  info: () => undefined,
  warn: () => undefined,
};

export function captureLog(): Logger & { entries: { obj: object; msg?: string }[] } {
  const entries: { obj: object; msg?: string }[] = [];
  return {
    entries,
    debug: (obj, msg) => entries.push({ obj, msg }),
    info: (obj, msg) => entries.push({ obj, msg }),
    warn: (obj, msg) => entries.push({ obj, msg }),
  };
}
