package usercenter

import (
	"log"
	"server/models"
	"sync"
	"time"
)

type UserCenter struct {
	activeCache sync.Map // 当前正在使用的主缓存
	backupCache sync.Map // 刷新期间使用的备用缓存
	mu          sync.Mutex
}

func NewUserCenter() *UserCenter {
	return &UserCenter{}
}

// LoadThreeDayUsers 分页加载最近三天登录的用户到备用缓存
func (uc *UserCenter) LoadThreeDayUsers() error {
	const batchSize = 1000 // 每次加载1000条记录
	skip := 0

	// 清空备用缓存
	uc.backupCache = sync.Map{}

	for {
		users, err := models.GetThreeDayUsersWithPagination(skip, batchSize)
		if err != nil {
			return err
		}

		// 如果没有更多用户，跳出循环
		if len(users) == 0 {
			break
		}

		// 将用户数据存入备用缓存
		for _, user := range users {
			uc.backupCache.Store(user.UserID, user)
		}

		skip += batchSize
	}

	log.Println("User data loaded into backup cache")
	return nil
}

// SwitchCache 切换主缓存与备用缓存
func (uc *UserCenter) SwitchCache() {
	uc.mu.Lock()
	defer uc.mu.Unlock()

	// 用备用缓存替换主缓存
	uc.activeCache, uc.backupCache = uc.backupCache, sync.Map{}
	log.Println("Cache switched successfully")
}

// GetUserFromCache 从主缓存中获取用户
func (uc *UserCenter) GetUserFromCache(userID int64) (*models.User, bool) {
	value, ok := uc.activeCache.Load(userID)
	if !ok {
		return nil, false
	}
	user, ok := value.(models.User)
	return &user, ok
}

// StartAutoRefresh 定期刷新备用缓存并切换
func (uc *UserCenter) StartAutoRefresh(interval time.Duration) {
	go func() {
		ticker := time.NewTicker(interval)
		defer ticker.Stop()

		for range ticker.C {
			log.Println("Starting to refresh user cache...")
			err := uc.LoadThreeDayUsers()
			if err != nil {
				log.Printf("Failed to refresh user cache: %v", err)
				continue
			}
			uc.SwitchCache() // 切换缓存
		}
	}()
}
