package service

import (
	"context"
	"encoding/base64"
	"encoding/json"
	"merchant/internal/config"
	"merchant/internal/utils"
	"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:    "merchant",
		UserId:      userId,
	}
	tokenBytes, _ := json.Marshal(tokenStruct)
	secretCfg := config.GetSecret()
	tokenB, err := utils.AesCBCEncrypt(tokenBytes, []byte(secretCfg.Key), []byte(secretCfg.IV))
	if err == nil {
		token = base64.URLEncoding.EncodeToString(tokenB)
	} else {
		token = ""
	}
	return token
}

var tokenService *TokenService

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