package server

import (
	"context"
	"time"

	"github.com/tidbcloud/AgentTeam/internal/config"
)

type publicRepoCacheWorker interface {
	RefreshDue(context.Context, int) (int, error)
	CleanupStaleGenerations(context.Context, int) (int, error)
}

func publicRepoCachePeriodicWorkers(cfg config.KBConfig, cache publicRepoCacheWorker) []kbPeriodicWorker {
	interval := cfg.PublicRepoCacheRefreshInterval
	if interval <= 0 {
		interval = time.Minute
	}
	return []kbPeriodicWorker{
		{
			interval:  interval,
			component: "public_repo_cache_refresh",
			errMsg:    "public repository cache refresh failed",
			run: func(ctx context.Context) error {
				if cache == nil {
					return nil
				}
				_, err := cache.RefreshDue(ctx, cfg.PublicRepoCacheRefreshBatch)
				return err
			},
		},
		{
			interval:       interval,
			runImmediately: true,
			component:      "public_repo_cache_cleanup",
			errMsg:         "public repository cache generation cleanup failed",
			run: func(ctx context.Context) error {
				if cache == nil {
					return nil
				}
				_, err := cache.CleanupStaleGenerations(ctx, cfg.PublicRepoCacheRefreshBatch)
				return err
			},
		},
	}
}
