package handler

import (
	"log"
	"net/http"
	"time"

	"mengyamonitor-backend-server/internal/hub"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

var wsUpgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

// MonitorWebSocket upgrades to WebSocket and streams hub snapshots.
func MonitorWebSocket(h *hub.Hub) gin.HandlerFunc {
	return func(c *gin.Context) {
		conn, err := wsUpgrader.Upgrade(c.Writer, c.Request, nil)
		if err != nil {
			log.Printf("ws: upgrade: %v", err)
			return
		}
		defer h.Unregister(conn)
		snap, err := h.BuildSnapshotMessage()
		if err != nil {
			_ = conn.Close()
			return
		}
		_ = conn.SetWriteDeadline(time.Now().Add(15 * time.Second))
		if err := conn.WriteMessage(websocket.TextMessage, snap); err != nil {
			_ = conn.Close()
			return
		}
		h.AddSubscriber(conn)
		for {
			_ = conn.SetReadDeadline(time.Now().Add(120 * time.Second))
			_, _, err := conn.ReadMessage()
			if err != nil {
				break
			}
		}
	}
}
