package chat

import (
	"context"
	"fmt"
	"math/rand"
	"time"

	"wechat-api/internal/svc"
	"wechat-api/internal/types"

	myjwt "github.com/golang-jwt/jwt/v4"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetAuthLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetAuthLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetAuthLogic {
	return &GetAuthLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx}
}

func (l *GetAuthLogic) GetAuth() (resp *types.BaseMsgResp, err error) {
	// todo: add your logic here and delete this line

	nowSec := time.Now().Unix()
	accessExpire := l.svcCtx.Config.Auth.AccessExpire
	accessSecret := l.svcCtx.Config.Auth.AccessSecret
	Id := RangeRandom(1, 99999)

	accessToken, err := getToken(accessSecret, nowSec, accessExpire, Id)
	if err != nil {
		accessToken = ""
	}
	msg := fmt.Sprintf("gen Token:'%s' by Id:%d and unixtime:%d \n", accessToken, Id, nowSec)
	return &types.BaseMsgResp{
		Code: 100,
		Msg:  msg,
	}, err
}

func getToken(secretKey string, iat, seconds, uid int64) (string, error) {
	claims := make(myjwt.MapClaims)
	claims["exp"] = iat + seconds
	claims["iat"] = iat
	claims["uid"] = uid
	token := myjwt.New(myjwt.SigningMethodHS256)
	token.Claims = claims
	return token.SignedString([]byte(secretKey))
}

// RangeRandom 返回指定范围内的随机整数。[min,max),不包含max
func RangeRandom(min, max int64) (number int64) {
	//创建随机种子
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	number = r.Int63n(max-min) + min
	return number
}
