package main

import (
	"context"
	"log"
	"net/http"

	"github.com/coder/websocket"
)

func main() {
	InitDatabase(context.Background())
	srv := &wsServer{
		OnOpen: func(ctx context.Context, conn *websocket.Conn) {
			log.Println("client connected")
			if getConnectionDataIfAuth(conn) != nil {
				mu.Lock()
				unauthenticatedConnections = append(unauthenticatedConnections, conn)
				mu.Unlock()
			}
		},
		OnClose: func(ctx context.Context, conn *websocket.Conn, err error) {
			log.Println("client disconnected:", err)
			removeConnectionCache(conn)
		},
		OnMessage: func(ctx context.Context, conn *websocket.Conn, msg map[string]any) {
			log.Printf("received: %v\n", msg)
			authConnOrNil := getConnectionDataIfAuth(conn)
			if authConnOrNil == nil {
				handleUnauthenticatedMessage(ctx, conn, msg)
			} else {
				handleAuthenticatedMessage(conn, msg)
			}
		},
	}

	http.Handle("/ws", srv)
	log.Println("server listening on :8080")
	log.Fatal(http.ListenAndServe(":8080", nil))
}
