package card_redeem_account

import (
	"context"
	"kami/internal/consts"
	"kami/internal/dao"
	"kami/internal/model/do"
	"kami/internal/model/entity"
	"kami/utility/cache"
	"kami/utility/config"
	"kami/utility/utils"

	"github.com/duke-git/lancet/v2/pointer"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/gogf/gf/v2/os/gtimer"
)

// UpdateStatus 更新账号状态
func (a *sCardRedeemAccount) UpdateStatus(ctx context.Context, id string, status consts.RedeemAccountStatus, tx gdb.TX) (err error) {
	m := dao.V1CardRedeemAccountInfo.Ctx(ctx).DB(config.GetDatabaseV1())
	if tx != nil {
		m = m.TX(tx)
	}
	if status == consts.RedeemAccountForbiddenByTooFast {
		_ = cache.NewCache().Set(ctx, string(cache.RedeemAccountTmpStopped)+id, 1, gtime.M)
		gtimer.AddOnce(context.Background(), gtime.M*2, func(ctx context.Context) {
			a.CheckForbiddenByTooFast(ctx)
		})
	}
	_, err = m.Where(dao.V1CardRedeemAccountInfo.Columns().Id, id).
		Update(do.V1CardRedeemAccountInfo{
			Status: status,
		})
	err = utils.HandleNoRowsError(err)
	return
}

// CheckForbiddenByTooFast 检查当前临时封禁账号是否解封
func (a *sCardRedeemAccount) CheckForbiddenByTooFast(ctx context.Context) {
	data := make([]entity.V1CardRedeemAccountInfo, 0)
	_ = dao.V1CardRedeemAccountInfo.Ctx(ctx).DB(config.GetDatabaseV1()).
		Where(dao.V1CardRedeemAccountInfo.Columns().Status, consts.RedeemAccountForbiddenByTooFast).Scan(&data)
	for _, datum := range data {
		//如果当前锁已经释放
		result, _ := cache.NewCache().Get(ctx, string(cache.RedeemAccountTmpStopped)+datum.Id)
		if pointer.IsNil(result) || result.IsNil() {
			_, _ = dao.V1CardRedeemAccountInfo.Ctx(ctx).DB(config.GetDatabaseV1()).
				Where(dao.V1CardRedeemAccountInfo.Columns().Id, datum.Id).Update(do.V1CardRedeemAccountInfo{
				Status: consts.RedeemAccountNormal,
			})
		}
	}
}
