package swagger_api

import (
	"embed"
	"encoding/json"
	"net/http"
	"net/url"

	"github.com/go-kratos/kratos/v2/api/metadata"
	"github.com/go-kratos/kratos/v2/transport/http/binding"
	"github.com/gorilla/mux"
)

//go:embed q/swagger-ui/*
var staticFS embed.FS

func NewHandler(servicesList []string, skipError bool) http.Handler {

	service := New(skipError)
	r := mux.NewRouter()

	r.HandleFunc("/q/services", func(w http.ResponseWriter, r *http.Request) {
		if len(servicesList) > 0 {
			w.Header().Set("Content-Type", "application/json")
			w.WriteHeader(200)
			reply := map[string][]string{
				"services": servicesList,
			}
			json.NewEncoder(w).Encode(reply)
		} else {
			services, err := service.ListServices(r.Context(), &metadata.ListServicesRequest{})
			if err != nil {
				w.WriteHeader(500)
				w.Write([]byte(err.Error()))
				return
			}
			w.Header().Set("Content-Type", "application/json")
			w.WriteHeader(200)
			json.NewEncoder(w).Encode(services)
		}
	}).Methods("GET")

	r.HandleFunc("/q/service/{name}", func(w http.ResponseWriter, r *http.Request) {
		raws := mux.Vars(r)
		vars := make(url.Values, len(raws))
		for k, v := range raws {
			vars[k] = []string{v}
		}
		var in metadata.GetServiceDescRequest
		if err := binding.BindQuery(vars, &in); err != nil {
			w.WriteHeader(400)
			w.Write([]byte(err.Error()))
			return
		}
		content, err := service.GetServiceOpenAPI(r.Context(), &in)
		if err != nil {
			w.WriteHeader(500)
			w.Write([]byte(err.Error()))
			return
		}

		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(200)
		w.Write([]byte(content))
	}).Methods("GET")

	staticServer := http.FileServer(http.FS(staticFS))
	sh := http.StripPrefix("", staticServer)
	//r.Handle("/q/swagger-ui/", sh)
	r.PathPrefix("/q/swagger-ui").Handler(sh)
	return r
}
