package main

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

	"github.com/quic-go/quic-go/http3"
	"github.com/quic-go/webtransport-go"
)

func main() {

	mux := http.NewServeMux()

	wt := &webtransport.Server{
		CheckOrigin: func(r *http.Request) bool { return true },
	}

	mux.HandleFunc("/chat", func(w http.ResponseWriter, r *http.Request) {

		session, err := wt.Upgrade(w, r)
		if err != nil {
			log.Println("upgrade error:", err)
			return
		}

		go handleChatSession(session)
	})

	server := http3.Server{
		Addr:    ":8080",
		Handler: mux,
	}

	fmt.Println("HTTP/3 server started")

	log.Fatal(server.ListenAndServe())
}

func handleChatSession(session *webtransport.Session) {

	for {
		stream, err := session.AcceptStream(context.Background())
		if err != nil {
			return
		}

		go func(s webtransport.Stream) {
			defer s.Close()

			buf := make([]byte, 1024)
			n, _ := s.Read(buf)

			fmt.Println("Message:", string(buf[:n]))

			s.Write([]byte("Server: OK"))
		}(*stream)
	}
}
