package test

import (
	"fmt"
	decorateCfg "server/conf/decorate"
	"server/db"
	"server/game"
	"server/pkg/github.com/name5566/leaf/log"
	"testing"
)

func TestFixDecorate(t *testing.T) {
	// Initialize player
	p := new(game.Player)
	p.FixDecorate()

	//
	p.InitPlayer("dee8eeb83ea3c54e48427b7ff20066fb")
	p.FixDecorate()

	DecorateMod := p.GetDecorateMod()
	DecorateMod.AreaId = 3
	DecorateMod.Progress = 22
	p.FixDecorate()
}

func TestFixUserData(t *testing.T) {
	// 确保数据库已初始化
	if db.SqlDb == nil {
		db.InitDB()
		// 等待初始化完成
		for i := 0; i < 10; i++ {
			if db.SqlDb != nil {
				break
			}
			log.Warn("Waiting for database initialization...")
			// time.Sleep(100 * time.Millisecond)
		}
	}

	if db.SqlDb == nil {
		t.Fatal("Database initialization failed")
	}

	log.Warn("hello world")
	type account struct {
		Account string `db:"user_name"`
	}
	var accounts []account
	sqlDb := db.GetDB() // 使用线程安全的方式获取连接
	if sqlDb == nil {
		t.Fatal("Database connection is nil")
	}
	err := sqlDb.Select(&accounts, "SELECT `user_name` FROM t_account order by auto_id")
	if err != nil {
		t.Errorf("Failed to fetch accounts: %v", err)
		return
	}
	i := 0
	for _, acc := range accounts {
		i++
		fmt.Printf("Fixing account %d/%d: %s\n", i, len(accounts), acc.Account)
		account := acc.Account
		p := new(game.Player)
		p.InitPlayer(account)
		DecorateMod := p.GetDecorateMod()
		if DecorateMod.PartCost == nil {
			return
		}
		for k := range DecorateMod.PartCost {
			AreaId := decorateCfg.GetAreaIdByIndoorId(k)
			if AreaId < DecorateMod.AreaId {
				log.Debug("Fixing account: %s, PartId: %d, OldAreaId: %d, NewAreaId: %d\n", account, k, AreaId, DecorateMod.AreaId)
			}
		}
		p.Stop()
		p = nil
	}
	log.Debug("All accounts fixed")
}
