import { Server } from "socket.io";
import { EVENTS } from "./events";
import { StatusSnapshot } from "../status/status.service";
import { LoopJob, TimerLog, TimerSummary } from "../types";
import { EnrichedWatcherItem, WatcherListItem, WatcherSummaryResponse } from "../watcher/watcher.types";

let io: Server | null = null;

export const initEmitter = (server: Server) => {
  io = server;
};

export const emitStatusSnapshot = (snapshot: StatusSnapshot) => {
  io?.emit(EVENTS.STATUS_SNAPSHOT, snapshot);
};

export const emitStatusUpdate = (snapshot: StatusSnapshot) => {
  io?.emit(EVENTS.STATUS_UPDATE, snapshot);
};

export const emitJobMetrics = (job: LoopJob) => {
  io?.emit(EVENTS.JOB_METRICS, job);
};

export const emitJobLog = (payload: {
  jobId: string;
  level: "INFO" | "WARN" | "ERROR";
  message: string;
  createdAt: string;
}) => {
  io?.emit(EVENTS.JOB_LOG, payload);
};

export const emitQbitHealth = (payload: StatusSnapshot["qbit"]) => {
  io?.emit(EVENTS.QBIT_HEALTH, payload);
};

export const emitTimerLog = (payload: TimerLog) => {
  io?.emit(EVENTS.TIMER_LOG, payload);
};

export const emitTimerSummary = (payload: TimerSummary) => {
  io?.emit(EVENTS.TIMER_SUMMARY, payload);
};

export const emitWatchersList = (payload: WatcherListItem[]) => {
  io?.emit(EVENTS.WATCHERS_LIST, payload);
};

export const emitWatcherItems = (payload: EnrichedWatcherItem[]) => {
  io?.emit(EVENTS.WATCHER_ITEMS, payload);
};

export const emitWatcherSummary = (payload: WatcherSummaryResponse) => {
  io?.emit(EVENTS.WATCHER_SUMMARY, payload);
};
