package user

import (
	mongodbmgr "server/db/mongodb"
	redismgr "server/db/redis"
	agentmanager "server/game/agentManager"
	"server/msg"

	"github.com/name5566/leaf/log"
)

// 查找用户信息是否已经存在 Redis 中
func GetUserInfoById(userId string) *msg.UserInfo {
	// 从 Redis 中获取用户数据
	userData, err := redismgr.GetUserInfoFromRedis(userId)
	if err != nil {
		log.Debug("Error fetching user info from Redis:", err)
		return nil
	}

	// 如果 Redis 中有数据，直接返回
	if userData != nil {
		log.Debug("User found in Redis: %s", userId)
		return userData
	}

	// 如果 Redis 中没有数据，检查 MongoDB
	log.Debug("User not found in Redis, checking MongoDB: %s", userId)
	userData, err = redismgr.GetUserInfoFromRedis(userId)
	if err != nil {
		log.Debug("Error fetching user info from MongoDB:", err)
		return nil
	}

	// 如果 MongoDB 中也没有数据，执行新增操作
	if userData == nil {
		log.Debug("User not found in MongoDB, creating new user: %s", userId)
		userData = &msg.UserInfo{
			UserId: userId,
		}

		// 保存到 MongoDB 和 Redis
		err = mongodbmgr.AddUser(userData)
		if err != nil {
			log.Debug("Error saving new user to MongoDB:", err)
			return nil
		}

		err = redismgr.SaveUserInfoToRedis(userData)
		if err != nil {
			log.Debug("Error saving new user to Redis:", err)
			return nil
		}
	}

	return userData
}

// 减少用户金币
func DecreaseUserCoin(coin int32, userId string) {
	userData := GetUserInfoById(userId)
	// 获取存储在 agent 中的 UserData
	// 减少用户积分
	userData.MCoin -= coin
	SetUserInfo(userData)
	// 打印更新日志
	log.Debug("User %s's coin decreased by %d. New balance: %d", userId, coin, userData)
}
func SetUserInfo(userData *msg.UserInfo) {
	redismgr.SaveUserInfoToRedis(userData)
	user_agent := agentmanager.GetAgentByUserID(userData.UserId)
	if user_agent != nil {
		user_agent.SetUserData(userData)
		user_agent.WriteMsg(&msg.UpdateUserInfo{
			Info: userData,
		})
	}
}

// 添加用户金币
func AddUserCoin(coin int32, userId string) {
	// 查找用户数据
	userData := GetUserInfoById(userId)

	// 更新用户的金币
	userData.MCoin += coin
	SetUserInfo(userData)
	// 打印更新日志
	log.Debug("User %s's points updated: %d", userId, userData)
}
