package main

import (
	"fmt"

	"github.com/gofiber/contrib/websocket"
)

var userWSChannels = make(map[string]*websocket.Conn)

// Function to send events to all clients
func sendEvent(userID string, event string, data string) {
	message := fmt.Sprintf(`{"event": "%s", "data": "%s"}`, event, data)
	sendWSMessage(userID, message)
}

func sendWSMessage(userID string, message string) {
	mu.Lock()
	defer mu.Unlock()

	conn, ok := userWSChannels[userID]
	if !ok {
		return
	}

	if err := conn.WriteMessage(websocket.TextMessage, []byte(message)); err != nil {
		fmt.Println("write:", err)
		conn.Close()
		delete(userWSChannels, userID)
	}
}

func handleWebSocket(c *websocket.Conn) {
	userID := c.Query("userID")
	if userID == "" {
		c.Close()
		return
	}

	mu.Lock()
	userWSChannels[userID] = c
	mu.Unlock()

	defer func() {
		mu.Lock()
		delete(userWSChannels, userID)
		mu.Unlock()
		c.Close()
	}()

	for {
		if _, _, err := c.ReadMessage(); err != nil {
			fmt.Println("read:", err)
			break
		}
	}
}
