package main

import (
	"flag"
	"log"
	"net/http"
	"path/filepath"

	"connectrpc.com/connect"

	"connectrpc.com/validate"
	"git.kocoder.xyz/kocoder/portforwarder/api/types/v1alpha1"
	clientV1alpha1 "git.kocoder.xyz/kocoder/portforwarder/clientset/v1alpha1"
	"git.kocoder.xyz/kocoder/portforwarder/gen/portforwarding/portforwardingv1connect"
	"git.kocoder.xyz/kocoder/portforwarder/portforwarding"
	"k8s.io/client-go/kubernetes/scheme"
	"k8s.io/client-go/tools/clientcmd"
	"k8s.io/client-go/util/homedir"
)

func main() {
	var kubeconfig *string
	if home := homedir.HomeDir(); home != "" {
		kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
	} else {
		kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
	}
	flag.Parse()

	// use the current context in kubeconfig
	config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
	if err != nil {
		panic(err.Error())
	}

	err = v1alpha1.AddToScheme(scheme.Scheme)
	if err != nil {
		panic(err.Error())
	}

	client, err := clientV1alpha1.NewForConfig(config)
	if err != nil {
		panic(err)
	}

	const namespace = "default"

	pf := portforwarding.NewPortforwardingService(client.Ingressroute(namespace), namespace, "external-db-svc", ".kocoder.xyz", "k3s-kocoder-xyz-tls")

	mux := http.NewServeMux()
	path, handler := portforwardingv1connect.NewPortForwardingServiceHandler(
		pf,
		connect.WithInterceptors(validate.NewInterceptor()),
	)

	mux.Handle(path, handler)
	p := new(http.Protocols)
	p.SetHTTP1(true)
	// Use h2c so we can serve HTTP/2 without TLS.
	p.SetUnencryptedHTTP2(true)
	s := http.Server{
		Addr:      "localhost:8080",
		Handler:   mux,
		Protocols: p,
	}
	err = s.ListenAndServe()
	log.Fatal(err)

	// ir := &v1alpha1.IngressRoute{
	// 	ObjectMeta: v1.ObjectMeta{
	// 		Name: "beary-times",
	// 	},
	// 	Spec: v1alpha1.IngressRouteSpec{
	// 		EntryPoints: []string{"websecure", "web"},
	// 		Routes: []v1alpha1.Route{
	// 			{
	// 				Kind:  "Rule",
	// 				Match: "Host(`beary-times.kocoder.xyz`)",
	// 				Services: []v1alpha1.Service{
	// 					{
	// 						Kind:               "Service",
	// 						Name:               "external-db-svc",
	// 						Namespace:          "default",
	// 						PassHostHeader:     false,
	// 						Port:               63419,
	// 						ResponseForwarding: v1alpha1.ResponseForwarding{FlushInterval: "10ms"},
	// 						Scheme:             "https",
	// 						Sticky:             v1alpha1.Sticky{Cookie: v1alpha1.Cookie{HttpOnly: false, Name: "", Secure: false}},
	// 						Strategy:           "wrr",
	// 						Weight:             0,
	// 					},
	// 				},
	// 				Middlewares:   []v1alpha1.Middleware{},
	// 				Observability: v1alpha1.Observability{AccessLogs: true, Metrics: true, Tracing: true},
	// 				Priority:      10,
	// 			},
	// 		},
	// 	},
	// }

	// ir, err = client.Ingressroute("default").Create(context.TODO(), ir)
	// if err != nil {
	// 	panic(err)
	// }

	// client.Ingressroute("default").Delete(context.TODO(), "hannes", v1.DeleteOptions{})
}
