package dao

import (
	"gorm.io/gorm"
)

type Character struct {
	ID            int32  `gorm:"primaryKey;type:int;not null;comment:'角色ID'"`
	VoiceId       int    `gorm:"type:int;default null;comment:'声音ID'"`
	AvatarId      string `gorm:"type:varchar(32);not null;comment:'角色头像的uuid'"`
	BackgroundIds string `gorm:"type:varchar(255);not null;comment:'聊天背景图集合，逗号分隔，元素是背景图的uuid'"`
	Name          string `gorm:"type:varchar(32);not null;comment:'角色名称'"`
	WakeupWords   string `gorm:"type:varchar(255);not null;"`
	WorldScenario string `gorm:"type:mediumtext;not null;"`
	Description   string `gorm:"type:mediumtext;not null;"`
	Emojis        string `gorm:"type:json;not null;"`
	Dialogues     string `gorm:"type:mediumtext;not null;"`
}

func (Character) TableName() string { return "character" }

func Character_Insert(data *Character) (int32, error) {
	if err := s.db.Create(data).Error; err != nil {
		return 0, err
	}
	return data.ID, nil
}

func Character_Query(characterId int32) (*Character, error) {
	var data Character
	err := s.db.Where("id = ?", characterId).First(&data).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		}
		return nil, err
	}
	return &data, nil
}

func Character_QueryAllCharacter() ([]*Character, error) {
	var list []*Character
	err := s.db.Find(&list).Error
	if err != nil {
		return nil, err
	}
	return list, nil
}

// 根据角色ID列表，查询信息
func Character_QueryList(characterIds []int32) ([]*Character, error) {
	var list []*Character
	if err := s.db.Find(&list, characterIds).Error; err != nil {
		return nil, err
	}
	return list, nil
}

func Character_Delete(characterId int32) error {
	return s.db.Delete(&Character{}, characterId).Error
}

type CharacterBaseInfo struct {
	ID       int32  `gorm:"id"`
	AvatarId string `gorm:"avatar_id"`
	Name     string `gorm:"name"`
}

// 根据头像的ID列表，查询头像和名称信息
func Character_QueryList_BaseInfo(characterIds []int32) ([]*CharacterBaseInfo, error) {
	var list []*CharacterBaseInfo
	if err := s.db.Model(&Character{}).Where("id in (?)", characterIds).Select("id, avatar_id, name").Scan(&list).Error; err != nil {
		return nil, err
	}
	return list, nil
}
