package main

import (
	"log"
	"net/http"

	"connectrpc.com/grpcreflect"
	servicepb "github.com/chathaway-codes/home-sensors/v2/gen/genconnect"
	"github.com/chathaway-codes/home-sensors/v2/pkg/signaler"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"github.com/rs/cors"
)

func main() {
	mux := http.NewServeMux()
	reflector := grpcreflect.NewStaticReflector(
		servicepb.SignalerServiceName,
	)
	mux.Handle(grpcreflect.NewHandlerV1(reflector))
	mux.Handle(grpcreflect.NewHandlerV1Alpha(reflector))
	mux.Handle(servicepb.NewSignalerServiceHandler(signaler.New()))

	corsHandler := cors.New(cors.Options{
		AllowedMethods: []string{
			http.MethodGet,
			http.MethodPost,
		},
		AllowedOrigins: []string{"*"},
		AllowedHeaders: []string{
			"Accept-Encoding",
			"Authorization",
			"Content-Encoding",
			"Content-Type",
			"Connect-Protocol-Version",
			"Connect-Timeout-Ms",
			"Connect-Accept-Encoding",  // Unused in web browsers, but added for future-proofing
			"Connect-Content-Encoding", // Unused in web browsers, but added for future-proofing
			"Grpc-Timeout",             // Used for gRPC-web
			"X-Grpc-Web",               // Used for gRPC-web
			"X-User-Agent",             // Used for gRPC-web
		},
		ExposedHeaders: []string{
			"Content-Encoding",         // Unused in web browsers, but added for future-proofing
			"Connect-Content-Encoding", // Unused in web browsers, but added for future-proofing
			"Grpc-Status",              // Required for gRPC-web
			"Grpc-Message",             // Required for gRPC-web
		},
	})
	mux.Handle("/metrics", promhttp.Handler())
	handler := corsHandler.Handler(mux)

	server := &http.Server{
		Addr:    "0.0.0.0:8080",
		Handler: handler,
		//Handler: h2c.NewHandler(handler, &http2.Server{}),

	}

	if err := server.ListenAndServeTLS("server.crt", "server.key"); err != nil {
		log.Fatalf("Failed to listen for HTTP traffic: %v", err)
	}
}
