import { EventEmitter } from "node:events";

export type PMEvent =
  | { type: "project.updated"; projectId: string }
  | { type: "commit.new"; projectId: string; hash: string }
  | { type: "scan.complete"; added: number; updated: number }
  | { type: "deploy.update"; deployId: string; status: string }
  | { type: "deploy.log"; deployId: string; line: string };

class Bus {
  private emitter = new EventEmitter();
  private static globalKey = Symbol.for("pm.eventBus.singleton");

  static instance(): Bus {
    const g = globalThis as unknown as Record<symbol, Bus>;
    if (!g[Bus.globalKey]) g[Bus.globalKey] = new Bus();
    return g[Bus.globalKey];
  }

  emit(event: PMEvent): void {
    this.emitter.emit("pm", event);
  }

  subscribe(handler: (event: PMEvent) => void): () => void {
    this.emitter.on("pm", handler);
    return () => this.emitter.off("pm", handler);
  }
}

export const eventBus = Bus.instance();
