package model

import (
	"time"

	"github.com/sirupsen/logrus"
	"gogs.daxia.dev/huanan/pkg.daxia.dev/db"
	"gorm.io/gorm"
)

type GameDisable struct {
	gorm.Model

	UserID    int32
	ExpiredAt time.Time
}

func (GameDisable) TableName() string {
	return "game_disable"
}

func (p GameDisable) Init() error {
	var err error

	if !db.GetDB().Migrator().HasTable(p) {
		err = db.GetDB().Migrator().CreateTable(p)
		if err != nil {
			logrus.Error(err)
			return err
		}

		err = db.GetDB().Exec("create unique index idx_user_id on game_disable (user_id)").Error
		if err != nil {
			return err
		}

	}

	return nil
}

func (p GameDisable) IsDisable(userID int32) (bool, error) {
	gameDisableModel := GameDisable{}
	err := db.GetDB().Model(p).Where("user_id = ?", userID).First(&gameDisableModel).Error
	if err == gorm.ErrRecordNotFound {
		return false, nil
	}

	if err != nil {
		return false, err
	}

	if time.Now().Before(gameDisableModel.ExpiredAt) {
		return true, nil
	}

	return false, nil
}
