package dao

import (
	"time"

	"gorm.io/gorm"
)

type ChatRecord struct {
	ID          uint64    `gorm:"primaryKey;not null;comment:'聊天记录ID'"`
	CreatedAt   time.Time `gorm:"index;type:datetime(0);comment:'记录时间，由数据库自动创建'"`
	UserId      int32     `gorm:"index;not null;comment:'用户Id'"`
	CharacterId int32     `gorm:"index;not null;comment:'角色Id'"`
	Direction   int8      `gorm:"comment:'发送方向。1:用户->角色。 2:角色->用户'"`
	Message     string    `gorm:"type:text;not null;comment:'消息内容'"`
}

func ChatRecord_Query(user_id, character_id int32, start_time, stop_time time.Time) ([]*ChatRecord, error) {
	var list []*ChatRecord
	if err := s.db.Where("user_id = ? and character_id = ?", user_id, character_id).Where("created_at between ? and ?", start_time, stop_time).Find(&list).Error; err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return list, nil
}

func ChatRecord_Insert(data *ChatRecord) error {
	return s.db.Create(data).Error
}

// 查询用户和所有角色聊天记录。
func ChatRecord_Query_ByUserId(user_id int32, start_time, stop_time time.Time) ([]*ChatRecord, error) {
	var list []*ChatRecord
	if err := s.db.Where("user_id = ?", user_id).Where("created_at between ? and ?", start_time, stop_time).Find(&list).Error; err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return list, nil
}

// 查询用户和角色是否有聊天记录
func ChatRecord_Exists(user_id, character_id int32) (bool, error) {
	id := int32(0)
	if err := s.db.Model(&ChatRecord{}).Where("user_id = ? and character_id = ?", user_id, character_id).Limit(1).Select("id").Scan(&id).Error; err != nil && err != gorm.ErrRecordNotFound {
		return false, err
	}
	return id > int32(0), nil
}
