import { Server as HttpServer } from "http";
import { Server as SocketServer } from "socket.io";

let io: SocketServer;

export function initSocket(httpServer: HttpServer) {
  io = new SocketServer(httpServer, {
    cors: { origin: "*", methods: ["GET", "POST"] },
  });

  io.on("connection", (socket) => {
    socket.on("join:org", (orgId: string) => {
      socket.join(`org:${orgId}`);
    });
  });

  return io;
}

export function getIO() {
  if (!io) throw new Error("Socket.IO not initialized");
  return io;
}

export function emitTaskStatusUpdate(
  orgId: string,
  payload: { taskId: string; status: string; clientId?: string },
) {
  if (!io) return;
  io.to(`org:${orgId}`).emit("task:statusUpdated", payload);
}

export function emitPaymentUpdate(
  orgId: string,
  payload: { invoiceId: string; status: string; taskId?: string | null },
) {
  if (!io) return;
  io.to(`org:${orgId}`).emit("payment:updated", payload);
}
