package middleware

import (
	"fmt"

	"github.com/gin-gonic/gin"
	"github.com/unrolled/secure"
)

// TLSConfig TLS配置
type TLSConfig struct {
	// SSLHost SSL主机地址（例如：localhost:443）
	SSLHost string
	// SSLRedirect 是否重定向到HTTPS
	SSLRedirect bool
}

// 默认TLS配置
var defaultTLSConfig = TLSConfig{
	SSLHost:     "localhost:443",
	SSLRedirect: true,
}

// SetTLSConfig 设置TLS配置
func SetTLSConfig(cfg TLSConfig) {
	defaultTLSConfig = cfg
}

// LoadTls TLS加载中间件（与 kra 保持一致）
// 用https把这个中间件在router里面use一下就好
func LoadTls() gin.HandlerFunc {
	return func(c *gin.Context) {
		middleware := secure.New(secure.Options{
			SSLRedirect: defaultTLSConfig.SSLRedirect,
			SSLHost:     defaultTLSConfig.SSLHost,
		})
		err := middleware.Process(c.Writer, c.Request)
		if err != nil {
			// 如果出现错误，请不要继续
			fmt.Println(err)
			return
		}
		// 继续往下处理
		c.Next()
	}
}

// LoadTlsWithConfig 使用自定义配置的TLS加载中间件
func LoadTlsWithConfig(cfg TLSConfig) gin.HandlerFunc {
	return func(c *gin.Context) {
		middleware := secure.New(secure.Options{
			SSLRedirect: cfg.SSLRedirect,
			SSLHost:     cfg.SSLHost,
		})
		err := middleware.Process(c.Writer, c.Request)
		if err != nil {
			fmt.Println(err)
			return
		}
		c.Next()
	}
}
