package main

import (
	"context"
	"crypto/tls"
	"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
		}

		log.Println("WebTransport session opened")

		go handleSession(session)
	})

	tlsConfig := &tls.Config{
		Certificates: make([]tls.Certificate, 1),
		NextProtos: []string{
			"h3",
		},
	}

	var err error
	tlsConfig.Certificates[0], err = tls.LoadX509KeyPair(
		"qgo.quizer.space.pem",
		"qgo.quizer.space-key.pem",
	)
	if err != nil {
		log.Fatal(err)
	}

	server := http3.Server{
		Addr:      ":4443",
		Handler:   mux,
		TLSConfig: tlsConfig,
	}

	fmt.Println("WebTransport server running on :4443")

	err = server.ListenAndServe()
	if err != nil {
		log.Fatal(err)
	}
}

func handleSession(session *webtransport.Session) {

	for {

		stream, err := session.AcceptStream(context.Background())
		if err != nil {
			log.Println("session closed:", err)
			return
		}

		go handleStream(stream)
	}
}

func handleStream(stream *webtransport.Stream) {

	defer stream.Close()

	buf := make([]byte, 1024)

	n, err := stream.Read(buf)
	if err != nil {
		return
	}

	msg := string(buf[:n])

	fmt.Println("Message:", msg)

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