package taskcenter

import (
	tcmodel "bindbox-game/internal/repository/mysql/task_center"
	"context"
	"encoding/json"
	"time"

	"gorm.io/gorm"
)

const activeTasksCacheKey = "task_center:active_tasks"

func (s *service) invalidateCache(ctx context.Context) error {
	if s.redis == nil {
		return nil
	}
	return s.redis.Del(ctx, activeTasksCacheKey).Err()
}

func (s *service) getActiveTasks(ctx context.Context) ([]tcmodel.Task, error) {
	// 1. Try Redis
	if s.redis != nil {
		val, err := s.redis.Get(ctx, activeTasksCacheKey).Result()
		if err == nil {
			var tasks []tcmodel.Task
			if err := json.Unmarshal([]byte(val), &tasks); err == nil {
				return tasks, nil
			}
		}
	}

	// 2. Fallback to DB
	var tasks []tcmodel.Task
	if err := s.repo.GetDbR().Preload("Tiers", func(db *gorm.DB) *gorm.DB {
		return db.Order("priority asc, id asc")
	}).Preload("Rewards").Where("status=1").Find(&tasks).Error; err != nil {
		return nil, err
	}

	// 3. Write back to Redis
	if s.redis != nil && len(tasks) > 0 {
		b, _ := json.Marshal(tasks)
		_ = s.redis.Set(ctx, activeTasksCacheKey, string(b), 1*time.Hour).Err()
	}

	return tasks, nil
}
