package middleware

import (
	"context"
	"gitee.ltd/lxh/wechat-robot/internal/config"
	"gitee.ltd/lxh/wechat-robot/internal/logto"
	"gitee.ltd/lxh/wechat-robot/internal/redis"
	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/log"
)

// IsAuthenticated
// @description: 检查用户是否已登录
// @param c
// @return bool
func IsAuthenticated(c *fiber.Ctx) (loginType string, flag bool) {
	token := c.Cookies("auth_token")
	if token == "" {
		if token = c.Cookies("logto-session"); token == "" {
			return
		}
	}

	// 根据认证类型验证
	loginType = config.Scd.Auth.Type
	switch config.Scd.Auth.Type {
	case "password":
		// 对比token (简单实现，实际应用可能需要更复杂的验证)
		flag = token == config.Scd.Auth.Password.SecretKey
	case "logto":
		// 如果是Logto认证方式，检查token前缀，有前缀则认为已登录
		flag = redis.Client.Exists(context.Background(), token).Val() > 0
	default:
		// nothing
	}

	return
}

// Authenticate
// @description: 创建身份验证中间件
// @return fiber.Handler
func Authenticate() fiber.Handler {
	return func(c *fiber.Ctx) error {
		// 检查是否已登录
		loginType, flag := IsAuthenticated(c)
		if !flag {
			return c.Redirect("/login")
		}

		// 获取Logto客户端
		if loginType == "logto" {
			client, err := logto.GetLogtoClient(c)
			if err != nil {
				return c.Redirect("/error?error=Logto登录错误: " + err.Error())
			}
			if userInfo, e := client.GetIdTokenClaims(); e == nil {
				//log.Debugf("获取用户信息成功: %+v", userInfo)
				c.Locals("userId", userInfo.Sub)
			} else {
				log.Errorf("获取用户信息失败: %v", e)
			}
		}

		return c.Next()
	}
}
