import { WebSocketServer } from "ws"

let wss: WebSocketServer | null = null

export function initWebSocketServer(server: any) {
  if (wss) return wss

  wss = new WebSocketServer({ server })

  wss.on("connection", (ws) => {
    console.log("Admin connected to WebSocket")

    ws.on("message", (message) => {
      try {
        const data = JSON.parse(message.toString())
        if (data.type === "ping") {
          ws.send(JSON.stringify({ type: "pong" }))
        }
      } catch (err) {
        console.error("WebSocket message error:", err)
      }
    })

    ws.on("close", () => {
      console.log("Admin disconnected from WebSocket")
    })

    ws.on("error", (error) => {
      console.error("WebSocket error:", error)
    })
  })

  return wss
}

export function broadcastUpdate(data: any) {
  if (!wss) return

  const message = JSON.stringify({
    type: "update",
    data,
    timestamp: new Date().toISOString(),
  })

  wss.clients.forEach((client) => {
    if (client.readyState === 1) {
      // WebSocket.OPEN
      try {
        client.send(message)
      } catch (err) {
        console.error("Error sending WebSocket message:", err)
      }
    }
  })
}

export { wss }
