package sms

import (
	logger "eta/eta_mini_ht_api/common/component/log"
	stringUtils "eta/eta_mini_ht_api/common/utils/string"
	"eta/eta_mini_ht_api/models"
	"gorm.io/gorm"
	"time"
)

// VerificationRecord represents a record of verification request and status.
type VerificationRecord struct {
	ID              int                `gorm:"primaryKey;autoIncrement;type:bigint(20) unsigned"`
	Mobile          string             `gorm:"not null;comment:'手机号码';type:varchar(15)"`
	Code            string             `gorm:"not null;comment:'验证码';type:varchar(10)"`
	RequestTime     time.Time          `gorm:"default:CURRENT_TIMESTAMP;not null;comment:'请求时间'"`
	Status          VerificationStatus `gorm:"not null;comment:'操作状态';type:enum('PENDING','VERIFIED','EXPIRED','FAILED')"`
	ExpiredTime     time.Time          `gorm:"not null;comment:'过期时间'"`
	ExpiredDuration int                `gorm:"-"`
}

// VerificationStatus is an enumeration for the status field.
type VerificationStatus string

const (
	StatusPending  VerificationStatus = "PENDING"
	StatusVerified VerificationStatus = "VERIFIED"
	StatusExpired  VerificationStatus = "EXPIRED"
)

// BeforeCreate hook to set the current time as the request time before creating a new record.
func (v *VerificationRecord) BeforeCreate(tx *gorm.DB) (err error) {
	v.RequestTime = time.Now()
	v.ExpiredTime = v.RequestTime.Add(time.Duration(v.ExpiredDuration) * time.Minute)
	return
}

func UpdateVerificationRecordByCode(mobile string, code string, record VerificationRecord) (err error) {
	if stringUtils.IsEmptyOrNil(code) {
		logger.Info("code为空,不做更新")
		return
	}
	conditions := map[string]interface{}{
		"mobile": mobile,
		"code":   code,
	}
	err = updateByConditions(conditions, record)
	if err != nil {
		logger.Error("更新验证码状态失败:%v", err)
	}
	return
}
func ExpiredCodesByTask() (err error) {
	db := models.Main()
	err = db.Model(&VerificationRecord{}).Where("expired_time < ?", time.Now()).Where("status =?", StatusPending).Update("status", StatusExpired).Error
	if err != nil {
		logger.Error("批量过期验证码失败:%v", err)
	}
	return
}
func updateByConditions(conditions map[string]interface{}, record VerificationRecord) (err error) {
	db := models.Main()
	// 使用 conditions 构建 WHERE 条件
	for k, v := range conditions {
		db = db.Where(k, v)
	}
	err = db.Updates(record).Error
	if err != nil {
		logger.Error("更新验证码记录失败:%v", err)
	}
	return
}
func InsertVerificationRecord(record VerificationRecord) (smId int, err error) {
	err = models.Main().Create(&record).Error
	if err != nil {
		logger.Error("插入验证码记录失败:%v", err)
	}
	smId = record.ID
	return
}
