package api

import (
	"io"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/olivere/elastic/v7"
	"github.com/rs/zerolog/log"
	"gitlab.com/tensorsecurity-rd/waf-console/cmd/api-server/config"
	"gitlab.com/tensorsecurity-rd/waf-console/internal/middleware"
	"gitlab.com/tensorsecurity-rd/waf-console/internal/utils"
	"gorm.io/gorm"
)

func SetRouters(db *gorm.DB, clusterClientManager *utils.ClusterClientManager, gatewayUrl string, ssoUrl string,
	elasticClient *elastic.Client, debug bool, regionUrlMap map[string]string) *gin.Engine {
	var engine *gin.Engine

	if !debug {
		// 生产模式
		log.Info().Msg("release mode")
		engine = ReleaseRouter()
		engine.Use(
			middleware.AuthMiddleware(ssoUrl),
		// middleware.RequestCostHandler(),
		// middleware.CustomLogger(),
		// middleware.CustomRecovery(),
		// middleware.CorsHandler(),
		// middleware.CorsHandler(),
		)
	} else {
		// 开发调试模式
		log.Info().Msg("debug mode")
		engine = gin.New()
		engine.Use(
			middleware.AuthMiddleware(ssoUrl),
			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, gatewayUrl, elasticClient, regionUrlMap)

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

	return engine
}

func SetApiRouters(config *config.Config, ssoUrl string, elasticClient *elastic.Client) *gin.Engine {
	var engine *gin.Engine

	if !config.Debug {
		// 生产模式
		log.Info().Msg("release mode")
		engine = ReleaseRouter()
		engine.Use(
			middleware.AuthMiddleware(ssoUrl),
		// middleware.RequestCostHandler(),
		// middleware.CustomLogger(),
		// middleware.CustomRecovery(),
		// middleware.CorsHandler(),
		// middleware.CorsHandler(),
		)
	} else {
		// 开发调试模式
		log.Info().Msg("debug mode")
		engine = gin.New()
		engine.Use(
			middleware.AuthMiddleware(ssoUrl),
			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!",
		})
	})

	SetWafProxyRouter(engine, config.RegionConfigs)
	return engine
}

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

	engine := gin.New()

	return engine
}
