package api

import (
	"context"
	"net/http"

	"google.golang.org/grpc"

	"github.com/grpc-ecosystem/grpc-gateway/runtime"

	"code.justin.tv/dta/rockpaperscissors/internal/api/swagger"
	pb "code.justin.tv/dta/rockpaperscissors/proto"
)

// NewGatewayMux properly initializes the grpc-gateway.
// endpoint is an address:port string for the gRPC service it forwards requests to.
func NewGatewayMux(ctx context.Context, endpoint string) (http.Handler, error) {
	mux := runtime.NewServeMux()

	dialOpts := []grpc.DialOption{grpc.WithInsecure()}

	err := pb.RegisterProjectMetadataServiceHandlerFromEndpoint(
		ctx, mux, endpoint, dialOpts)
	if err != nil {
		return nil, err
	}
	err = pb.RegisterEventServiceHandlerFromEndpoint(
		ctx, mux, endpoint, dialOpts)
	if err != nil {
		return nil, err
	}
	err = pb.RegisterMetricServiceHandlerFromEndpoint(
		ctx, mux, endpoint, dialOpts)
	if err != nil {
		return nil, err
	}

	serveMux := http.NewServeMux()
	serveMux.Handle("/api/swagger/", http.FileServer(swagger.AssetFS()))
	serveMux.Handle("/", mux)
	return serveMux, nil
}
