package handle

import (
	"context"
	"encoding/json"
	"fmt"
	"git.echol.cn/loser/logger/log"
	"github.com/go-oauth2/oauth2/v4"
	"github.com/google/uuid"
	"miniapp/client"
	"miniapp/model/common/constant"
	"strings"
)

func NewAccessGenerate() *AccessGenerate {
	return &AccessGenerate{}
}

type AccessGenerate struct {
}

// Token 手动实现Token生成，直接生成UUID，替换掉自带的那个憨得一批的长长的字符串
func (ag *AccessGenerate) Token(ctx context.Context, data *oauth2.GenerateBasic, isGenRefresh bool) (string, string, error) {
	u, _ := uuid.NewUUID()
	access := strings.ReplaceAll(u.String(), "-", "")

	refresh := ""
	if isGenRefresh {
		u, _ = uuid.NewUUID()
		refresh = strings.ReplaceAll(u.String(), "-", "")
	}
	// 生成新的，清理掉旧的
	ag.clearOldToken(ctx, data.UserID)
	// 返回结果
	return access, refresh, nil
}

// 清理掉旧的Token和RefreshToken
func (ag *AccessGenerate) clearOldToken(ctx context.Context, userId string) {
	rdsKey := constant.OAuth2RedisKey + "*-*"
	// 获取所有符合条件的Key
	keys, err := client.Redis.Keys(ctx, rdsKey).Result()
	if err != nil {
		log.Errorf("清理失败，跳过清理")
		return
	}
	for _, key := range keys {
		dataStr, err := client.Redis.Get(ctx, key).Result()
		if err != nil {
			continue
		}
		var m map[string]any
		if err = json.Unmarshal([]byte(dataStr), &m); err != nil {
			continue
		}
		// 找到匹配的数据
		if m["UserID"] == userId {
			// 删除AccessToken
			client.Redis.Del(ctx, fmt.Sprintf("%v%v", constant.OAuth2RedisKey, m["Access"]))
			client.Redis.Del(ctx, fmt.Sprintf("%v%v", constant.OAuth2RedisKey, m["Refresh"]))
			client.Redis.Del(ctx, key)
			continue
		}
	}
}
