package main

import (
	"context"
	"fmt"
	"net/http"
	"strings"
	"time"

	"git.vdhsn.com/barretthousen/barretthousen/src/lib/kernel"
	api "git.vdhsn.com/barretthousen/barretthousen/src/runner/api/grpc"
	"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
	"google.golang.org/grpc"
	"google.golang.org/grpc/backoff"
	"google.golang.org/grpc/credentials/insecure"
)

type ProxyAdminApp struct {
	LogLevel  kernel.LogLevel `yaml:"log_level" yaml-default:"0"`
	Port      int             `yaml:"port" `
	Endpoints struct {
		Runner string `yaml:"runner" `
	} `yaml:"endpoints"`
}

func (app *ProxyAdminApp) Start(ctx context.Context) error {
	grpcMux := runtime.NewServeMux()
	err := api.RegisterRunnerHandlerFromEndpoint(ctx, grpcMux, app.Endpoints.Runner, []grpc.DialOption{
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithConnectParams(grpc.ConnectParams{
			Backoff: backoff.Config{
				MaxDelay: time.Second * 3,
			},
			MinConnectTimeout: time.Second,
		}),
	})
	if err != nil {
		return err
	}

	kernel.TraceLog.Printf("%+v", app)

	httpServer := &http.Server{
		Addr:              fmt.Sprintf("0.0.0.0:%d", app.Port),
		ReadHeaderTimeout: time.Second,
		Handler: http.StripPrefix("/api", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			kernel.TraceLog.Printf("{ \"Client\": \"%s\", \"Path\":\"%s\", \"User-Agent\":\"%s\", \"Host\":\"%s\", \"Origin\":\"%s\"} ", r.RemoteAddr, r.URL, r.UserAgent(), r.Host, r.Header.Get("Origin"))

			if strings.HasPrefix(r.Host, "proxy-") {
				w.Header().Set("Access-Control-Allow-Origin", r.Header.Get("Origin"))
			}

			grpcMux.ServeHTTP(w, r)
		})),
	}

	kernel.InfoLog.Printf("Starting HTTP proxy @ %q", httpServer.Addr)

	return httpServer.ListenAndServe()
}

func (app *ProxyAdminApp) OnStop(ctx context.Context) {
}

func (app *ProxyAdminApp) GetLogLevel() kernel.LogLevel { return app.LogLevel }

func main() {
	kernel.Run(context.Background(), &ProxyAdminApp{
		LogLevel: kernel.LevelTrace,
		Port:     80,
	})
}
