package http

import (
	"encoding/json"
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"

	"github.com/tidbcloud/tidb-management-service/tempo-wrapper/pkg/version"
	"github.com/tidbcloud/tidb-management-service/utilities/allowlist"
)

// versionHandler outputs the current central server version information.
func versionHandler(w http.ResponseWriter, _ *http.Request) {
	data, _ := json.Marshal(version.Version())
	w.WriteHeader(http.StatusOK)
	_, _ = w.Write(data)
}

func registerLockList(g *gin.RouterGroup, allowList *allowlist.AllowLockList) {
	g.GET("/list", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"lock_list": fmt.Sprintf("%v", allowList.LockList.OrgIds),
		})
	})
	g.GET("/superuser", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"super_user": fmt.Sprintf("%v", allowList.LockList.SuperUsers),
		})
	})
}

func registerAllowList(g *gin.RouterGroup, allowList *allowlist.AllowLockList) {
	g.GET("/dedicated/rules", func(c *gin.Context) {
		rules, err := json.Marshal(allowList.DedicatedAllowList().Rules)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{
				"error": fmt.Sprintf("failed to marshal rules: %v", err),
			})
			return
		}

		c.JSON(http.StatusOK, gin.H{
			"dedicated_rules": rules,
		})
	})
}
