package main

import (
    "encoding/json"
    "log"
    "net/http"
    "time"
    "github.com/gorilla/websocket"
)

var clients = make(map[*websocket.Conn]bool)
var upgrader = websocket.Upgrader{}

type Event struct {
    GroupIdx  int   `json:"group_idx"`
    Timestamp int64 `json:"timestamp"`
}

func wsHandler(w http.ResponseWriter, r *http.Request) {
    upgrader.CheckOrigin = func(r *http.Request) bool { return true }
    conn, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Println("WebSocket upgrade error:", err)
        return
    }
    clients[conn] = true
    defer conn.Close()
    for {
        _, _, err := conn.ReadMessage()
        if err != nil {
            delete(clients, conn)
            break
        }
    }
}

func eventHandler(w http.ResponseWriter, r *http.Request) {
    var ev Event
    if err := json.NewDecoder(r.Body).Decode(&ev); err != nil {
        http.Error(w, "Bad request", http.StatusBadRequest)
        return
    }
    log.Printf("Olay alındı: %+v", ev)
    msg, _ := json.Marshal(ev)
    for conn := range clients {
        conn.WriteMessage(websocket.TextMessage, msg)
    }
    w.WriteHeader(http.StatusOK)
    w.Write([]byte("OK"))
}

func main() {
    http.HandleFunc("/ws", wsHandler)
    http.HandleFunc("/event", eventHandler)
    log.Println("Go microservice started at :8080")
    log.Fatal(http.ListenAndServe(":8080", nil))
}