package auth

import (
	"backend/pkg/permission/domain/entity"
	"context"
	"time"

	"backend/internal/svc"
	"backend/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

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

// NewRefreshTokenLogic 刷新 Access Token
func NewRefreshTokenLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RefreshTokenLogic {
	return &RefreshTokenLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RefreshTokenLogic) RefreshToken(req *types.RefreshTokenReq) (resp *types.RefreshTokenResp, err error) {
	data, err := l.svcCtx.TokenUC.ReadTokenBasicData(l.ctx, req.AccessToken)
	if err != nil {
		return nil, err
	}

	tk, err := l.svcCtx.TokenUC.RefreshToken(l.ctx, entity.RefreshTokenReq{
		Token:    req.RefreshToken,
		Scope:    "gateway",
		Expires:  time.Now().UTC().Add(l.svcCtx.Config.Token.RefreshTokenExpiry).Unix(),
		DeviceID: data["uid"],
	})
	if err != nil {
		return nil, err
	}

	return &types.RefreshTokenResp{
		AccessToken:  tk.Token,
		RefreshToken: tk.OneTimeToken,
		TokenType:    tk.TokenType,
	}, nil
}
