package ws

import (
	"net/http"

	"github.com/gorilla/websocket"
	"krates/server/internal/crdt"
)

type HandlerFunc func(*websocket.Conn, *http.Request) error

type WebSocketManager struct {
	crdtProvider *crdt.Provider
	upgrader     *websocket.Upgrader
}

func NewManager(crdtProvider *crdt.Provider) *WebSocketManager {
	return &WebSocketManager{
		crdtProvider: crdtProvider,
		upgrader: &websocket.Upgrader{
			CheckOrigin: func(r *http.Request) bool {
				return true
			},
		},
	}
}

func (m *WebSocketManager) WithWebSocket(handler HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		conn, err := m.upgrader.Upgrade(w, r, nil)
		if err != nil {
			http.Error(w, "WebSocket upgrade failed", http.StatusBadRequest)
			return
		}
		defer conn.Close()

		if err := handler(conn, r); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	}
}
