package share

import (
	"blazing/cool"
	"context"
	"time"

	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/util/gconv"
)

// newSessionStore 创建会话缓存实例
func newSessionStore() *cacheStore[uint32] {
	return &cacheStore[uint32]{
		manager: cool.CacheManager,
		prefix:  "blazing:session:",
	}
}

// newUserOnlineStore 创建用户在线状态缓存实例
func newUserOnlineStore() *cacheStore[uint16] {
	return &cacheStore[uint16]{
		manager: cool.CacheManager,
		prefix:  "blazing:useronline:",
	}
}

// sessionManager 会话管理器
type sessionManager struct {
	sessionStore    *cacheStore[uint32] // 会话缓存
	userOnlineStore *cacheStore[uint16] // 用户在线状态缓存
}

// newSessionManager 创建会话管理器
func newSessionManager() *sessionManager {
	return &sessionManager{
		sessionStore:    newSessionStore(),
		userOnlineStore: newUserOnlineStore(),
	}
}

// GetSession 通过会话ID获取用户ID
func (m *sessionManager) GetSession(sessionID string) (uint32, error) {
	return m.sessionStore.Get(context.Background(), sessionID)
}

// SaveSession 保存会话信息
func (m *sessionManager) SaveSession(sessionID string, userID uint32) error {
	return m.sessionStore.Set(gctx.New(), sessionID, userID, time.Hour*24)
}

// DeleteSession 删除会话
func (m *sessionManager) DeleteSession(sessionID string) error {
	return m.sessionStore.Del(gctx.New(), sessionID)
}

// SessionExists 检查会话是否存在
func (m *sessionManager) SessionExists(sessionID string) (bool, error) {
	return m.sessionStore.Contains(context.Background(), sessionID)
}

// SetUserOnline 设置用户在线状态
func (m *sessionManager) SetUserOnline(userID uint32, serverID uint16) error {
	return m.userOnlineStore.Set(gctx.New(), gconv.String(userID), serverID, 0)
}

// GetUserOnline 获取用户在线状态
func (m *sessionManager) GetUserOnline(userID uint32) (uint16, error) {
	return m.userOnlineStore.Get(context.Background(), gconv.String(userID))
}

// DeleteUserOnline 删除用户在线状态
func (m *sessionManager) DeleteUserOnline(userID uint32) error {
	return m.userOnlineStore.Del(gctx.New(), gconv.String(userID))
}

// UserOnlineExists 检查用户在线状态是否存在
func (m *sessionManager) UserOnlineExists(userID uint32) (bool, error) {
	return m.userOnlineStore.Contains(context.Background(), gconv.String(userID))
}
