package middleware

import (
	"fmt"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/stores/redis"
	"gitlab.fjmaimaimai.com/allied-creation/su-micro/pkg/tool"
)

type UserAuthService struct {
	redis     *redis.Redis
	appName   string
	checkAuth bool
}

func NewUserAuthService(redis *redis.Redis, appName string) UserAuthService {
	return UserAuthService{
		redis:   redis,
		appName: appName,
	}
}

// Refresh 刷新缓存的User Token
func (l UserAuthService) Refresh(userId int64, token string) error {
	err := l.redis.Set(l.CacheKey(userId), l.Hash(token))
	if err != nil {
		return err
	}
	return nil
}

// Compare 比较当前的Token是否已经过期
func (l UserAuthService) Compare(userId int64, token string) error {
	ok, err := l.redis.Exists(l.CacheKey(userId))
	if err != nil {
		return err
	}
	if !ok {
		return errors.New("Token not exists.") //l.Refresh(userId, token)
	}
	cacheToken, err := l.redis.Get(l.CacheKey(userId))
	if err != nil {
		return err
	}
	if !l.compare(cacheToken, token) {
		return errors.New("Token is expired.")
	}
	return nil
}

func (l UserAuthService) compare(cacheToken, token string) bool {
	if len(cacheToken) == len(token) && cacheToken == token {
		return true
	}
	if cacheToken == l.Hash(token) {
		return true
	}
	return false
}

// Hash token哈希编码
func (l UserAuthService) Hash(token string) string {
	return tool.Md5ByString(token)
}

func (l UserAuthService) CacheKey(userId int64) string {
	return fmt.Sprintf("%v:cache:%v:id:%v", l.appName, "user.auth", userId)
}