package api

import (
	"io"
	"net/http"

	"github.com/gin-gonic/gin"
	"gitlab.com/security-rd/go-pkg/logging"
	"gitlab.com/tensorsecurity-rd/waf-console/internal/config"
	"gitlab.com/tensorsecurity-rd/waf-console/internal/utils"
	"gorm.io/gorm"
)

func SetRouters(db *gorm.DB, clusterClientManager *utils.ClusterClientManager) *gin.Engine {
	var engine *gin.Engine

	if !config.Conf.Debug {
		// 生产模式
		logging.Get().Info().Msg("release mode")
		engine = ReleaseRouter()
		engine.Use(
		// middleware.RequestCostHandler(),
		// middleware.CustomLogger(),
		// middleware.CustomRecovery(),
		// middleware.CorsHandler(),
		)
	} else {
		// 开发调试模式
		logging.Get().Info().Msg("debug mode")
		engine = gin.New()
		engine.Use(
			// middleware.RequestCostHandler(),
			gin.Logger(),
			// middleware.CustomRecovery(),
			// middleware.CorsHandler(),
		)
	}
	// set up trusted agents
	err := engine.SetTrustedProxies([]string{"127.0.0.1"})
	if err != nil {
		panic(err)
	}
	// ping
	engine.GET("/ping", func(c *gin.Context) {
		c.AbortWithStatusJSON(http.StatusOK, gin.H{
			"message": "pong!",
		})
	})

	// 设置 API 路由
	// SetIPInforRouter(engine)
	// loadkubeConfig()
	// clientcmd.LoadFromFile("kubeconfig.yaml")
	// client := versioned.NewForConfigOrDie(&rest.Config{
	// 	Host: "https://127.0.0.1:6443",
	// 	TLSClientConfig: rest.TLSClientConfig{
	// 		Insecure: false,
	// 		CAData:   []byte(""),
	// 		CertData: []byte(""),
	// 		KeyData:  []byte(""),
	// 	},
	// 	// BearerToken: "1234567890",
	// })
	SetWafRouter(engine, clusterClientManager, db)

	// 统一处理 404
	engine.NoRoute(func(c *gin.Context) {
		utils.AssembleResponse(c, nil, err)
		// response2.Resp().SetHttpCode(http.StatusNotFound).FailCode(c, errors.NotFound)
	})

	return engine
}

// ReleaseRouter 生产模式使用官方建议设置为 release 模式
func ReleaseRouter() *gin.Engine {
	// 切换到生产模式
	gin.SetMode(gin.ReleaseMode)
	// 禁用 gin 输出接口访问日志
	gin.DefaultWriter = io.Discard

	engine := gin.New()

	return engine
}
