package application

import (
	"errors"
	"github.com/fonchain_enterprise/micro-account/pkg/m"
	"github.com/fonchain_enterprise/micro-account/pkg/model"
	"gorm.io/gorm"
	"time"
)

// AddRefreshToken 签发refreshtoken记录
func AddRefreshToken(token string) error {

	var count int64
	model.DB.Model(&model.RefreshToken{}).Where(&model.RefreshToken{RefreshToken: token}).Count(&count)

	if count > 0 {
		return nil
	}

	//记录登录信息
	refreshToken := &model.RefreshToken{
		RefreshToken: token,
		UseNum:       0,
		LastUseDate:  time.Now().Format("2006-01-02 15:04:05"),
		IsForbid:     model.IsForBid_No,
		ExpireDate:   time.Now().Add(time.Duration(m.RefreshTokenTime) * time.Hour).Format("2006-01-02 15:04:05"), //过期时间
	}

	return model.DB.Create(&refreshToken).Error
}

func CheckRefreshToke(token string) error {
	var refrshTokenObj *model.RefreshToken

	if err := model.DB.Model(&model.RefreshToken{}).Where(&model.RefreshToken{RefreshToken: token}).First(&refrshTokenObj).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return errors.New("this refresh_token is not exist")
		}
		return err
	}

	if refrshTokenObj.IsForbid == model.IsForBid_Yes {
		return errors.New("this refresh_token is forbidden")
	}

	if refrshTokenObj.UseNum > 0 {
		return errors.New("this refresh_token is used")
	}

	//记录登录信息
	updateLog := &model.RefreshToken{
		UseNum:      refrshTokenObj.UseNum + 1,
		LastUseDate: time.Now().Format("2006-01-02 15:04:05"),
	}

	return model.DB.Model(&model.RefreshToken{}).Where(&model.RefreshToken{ID: refrshTokenObj.ID}).Updates(&updateLog).Error
}
