package service

import (
	"boss/internal/config"
	"boss/internal/utils"
	"context"
	"encoding/base64"
	"encoding/hex"
	"encoding/json"
	"github.com/beego/beego/v2/core/logs"
	"sync"
	"time"
)

type TokenService struct {
}

func (t *TokenService) GetToken(ctx context.Context, userId string) (token string) {
	tokenStruct := struct {
		CurrentTime int64  `json:"currentTime"`
		UserId      string `json:"userId"`
		UserAuth    string `json:"userAuth"`
	}{
		CurrentTime: time.Now().Unix(),
		UserAuth:    "admin",
		UserId:      userId,
	}
	tokenBytes, _ := json.Marshal(tokenStruct)
	secretCfg, err := config.GetSecret()
	if err != nil {
		return ""
	}
	key, err := hex.DecodeString(secretCfg.Key)
	if err != nil {
		logs.Error(err)
		return ""
	}
	iv, err := hex.DecodeString(secretCfg.IV)
	if err != nil {
		logs.Error(err)
		return ""
	}
	tokenB, err := utils.AesCBCEncrypt(tokenBytes, key, iv)
	if err != nil {
		logs.Error(err)
		return ""
	}
	return base64.URLEncoding.EncodeToString(tokenB)
}

var tokenService *TokenService

func NewTokenService() *TokenService {
	sync.OnceFunc(func() {
		tokenService = &TokenService{}
	})()
	return tokenService
}
