package auth

import (
	"backend/internal/svc"
	"backend/internal/types"
	"backend/pkg/permission/domain/entity"
	"backend/pkg/permission/domain/token"
	"context"
	"time"
)

// 生成 Token
func generateToken(svc *svc.ServiceContext, ctx context.Context, req *types.LoginReq, uid string, role string) (entity.TokenResp, error) {
	tk, err := svc.TokenUC.NewToken(ctx, entity.AuthorizationReq{
		GrantType:      token.ClientCredentials.ToString(),
		DeviceID:       uid, // TODO 沒傳暫時先用UID 替代
		Scope:          "gateway",
		IsRefreshToken: true,
		Expires:        time.Now().UTC().Add(svc.Config.Token.AccessTokenExpiry).Unix(),
		Data: map[string]string{
			"uid": uid,
		},
		Role:    role,
		Account: req.LoginID,
	})
	if err != nil {
		return entity.TokenResp{}, err
	}

	return entity.TokenResp{
		AccessToken:  tk.AccessToken,
		TokenType:    tk.TokenType,
		ExpiresIn:    tk.ExpiresIn,
		RefreshToken: tk.RefreshToken,
	}, nil

}
