// Package router ...
//
// Description : router ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2025-02-18 17:26
package router

import (
	"git.zhangdeman.cn/zhangdeman/gin/middleware"
	"git.zhangdeman.cn/zhangdeman/rate_limit/abstract"
	"github.com/gin-gonic/gin"
)

type SetServerOptionFunc func(so *serverOption)

// serverOption 获取server实例的选项
type serverOption struct {
	docConfig            DocConfig                // 文档配置
	globalMiddlewareList []gin.HandlerFunc        // 全局中间件列表
	enablePprof          bool                     // 启用 pprof
	enableCors           bool                     // 启动跨域支持
	disableInitRequest   bool                     // 禁用初始化请求
	loggerCfg            *middleware.AccessConfig // 日志配置
	initContextData      gin.HandlerFunc          // 初始化一些请求数据
	rateLimitInstance    abstract.IRateLimit      // 服务流控实例
}

// WithRateLimitInstance 设置流控实例, 配置为 nil, 代表禁用
func WithRateLimitInstance(i abstract.IRateLimit) SetServerOptionFunc {
	return func(so *serverOption) {
		so.rateLimitInstance = i
	}
}

// WithDisableInitRequest 禁用自从初始化请求
func WithDisableInitRequest(disable bool) SetServerOptionFunc {
	return func(so *serverOption) {
		so.disableInitRequest = disable
	}
}

// WithInitContextData 初始化一些请求数据
func WithInitContextData(formatFunc func(ctx *gin.Context)) SetServerOptionFunc {
	return func(so *serverOption) {
		if nil == formatFunc {
			formatFunc = func(ctx *gin.Context) {}
		}

		so.initContextData = formatFunc
	}
}

// WithDocConfig 设置文档配置
func WithDocConfig(docConfig *DocConfig) SetServerOptionFunc {
	return func(so *serverOption) {
		if nil == docConfig {
			return
		}
		so.docConfig = *docConfig
	}
}

// WithGlobalMiddlewareList 设置全局中间件
func WithGlobalMiddlewareList(middlewareList ...gin.HandlerFunc) SetServerOptionFunc {
	return func(so *serverOption) {
		so.globalMiddlewareList = middlewareList
	}
}

// WithPprofEnable 启用pprof
func WithPprofEnable() SetServerOptionFunc {
	return func(so *serverOption) {
		so.enablePprof = true
	}
}

// WithEnableCors 启用全局跨域
func WithEnableCors() SetServerOptionFunc {
	return func(so *serverOption) {
		so.enableCors = true
	}
}

// WithLoggerCfg ...
func WithLoggerCfg(loggerCfg *middleware.AccessConfig) SetServerOptionFunc {
	return func(so *serverOption) {
		if nil != loggerCfg || nil != loggerCfg.Logger {
			so.loggerCfg = loggerCfg
		}
	}
}
