package ws

import (
	"log"
	"net/http"

	"github.com/gorilla/websocket"
)

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

// Hub representa um cliente WebSocket
var clients = make(map[*websocket.Conn]bool)
var broadcast = make(chan []byte)

// StartHub inicia o hub de websocket
func StartHub() {
	go func() {
		for {
			msg := <-broadcast
			for client := range clients {
				err := client.WriteMessage(websocket.TextMessage, msg)
				if err != nil {
					log.Printf("WebSocket erro: %v", err)
					client.Close()
					delete(clients, client)
				}
			}
		}
	}()
}

// HandleWS aceita conexões websocket
func HandleWS(w http.ResponseWriter, r *http.Request) {
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Printf("Erro ao fazer upgrade para websocket: %v", err)
		return
	}
	clients[conn] = true
	log.Println("Novo cliente WebSocket conectado")
}