package mysql

import (
	"context"
	"fmt"
	"pji_desktop_http/biz/dal/query"
	"pji_desktop_http/biz/model"
)

func AddWorld(ctx context.Context, world model.World) {
	w := query.World
	err := w.WithContext(ctx).Create(&world)
	if err != nil {
		panic(err)
	}
}

func QueryWorld(ctx context.Context, sceneId string) (*model.World, error) {
	w := query.World
	world, err := w.WithContext(ctx).Where(w.SceneID.Eq(sceneId)).Order(w.CreatedAt.Desc()).First()
	if err != nil {
		fmt.Println("Query world failed:", err.Error())
		return nil, err
	}
	fmt.Print("Query world successfully:", world)
	return world, err
}

// UpdateWorld 更新world记录
// updateValue中SceneID字段不能为空
func UpdateWorld(ctx context.Context, updateValue model.World) error {
	w := query.World
	fmt.Println("updateValue.SceneID", updateValue.SceneID)
	// 查询对应场景最新的记录
	world, err := w.WithContext(ctx).Where(w.SceneID.Eq(updateValue.SceneID)).Order(w.CreatedAt.Desc()).First()
	// 根据id更新对应记录
	if err != nil {
		return err
	}
	res, err := w.WithContext(ctx).Where(w.ID.Eq(world.ID)).Updates(updateValue)
	fmt.Println("res", res)
	if err != nil {
		fmt.Println("Update world failed:", err.Error())
		return err
	}
	world, err = w.WithContext(ctx).Where(w.ID.Eq(world.ID)).First()
	fmt.Print("Update world successfully:", world)
	return nil
}