import { EventEmitter } from "events";

export type TestEvent = {
  type: "test";
  userId: string;
};

export type MatchEvent = {
  type: "match";
  matchId: string;
  tournamentId: string;
};

export type ReactionEvent = {
  type: "reaction";
  matchId: string;
  reactions: Array<{
    emoji: string;
    count: number;
    players: Array<{ id?: string; first_name?: string; last_name?: string }>;
  }>;
};

export type TournamentEvent = {
  type: "tournament";
  tournamentId: string;
};

export type TeamEvent = {
  type: "team";
  teamId?: string;
};

export type PlayerEvent = {
  type: "player";
  playerId: string;
};

export type BadgeEvent = {
  type: "badge";
  playerId?: string;
};

export type ServerEvent =
  | TestEvent
  | MatchEvent
  | ReactionEvent
  | TournamentEvent
  | TeamEvent
  | PlayerEvent
  | BadgeEvent;

export const EVENT_TYPES = [
  "test",
  "match",
  "reaction",
  "tournament",
  "team",
  "player",
  "badge",
] as const satisfies readonly ServerEvent["type"][];

export const serverEvents = new EventEmitter();

serverEvents.setMaxListeners(200);

export const emitServerEvent = (event: ServerEvent) => {
  serverEvents.emit(event.type, event);
};

if (process.env.NODE_ENV === 'development') {
  setInterval(() => {
    const listenerCounts = Object.fromEntries(
      EVENT_TYPES.map((type) => [type, serverEvents.listenerCount(type)])
    );

    if (Object.values(listenerCounts).some((count) => count > 0)) {
      console.log('ServerEvents listener count:', listenerCounts);
    }
  }, 30000);
}
