package async

import (
	"context"
	"runtime/debug"
	"sundynix-go/global"
	"sync"
	"time"

	"go.uber.org/zap"
)

type AsyncTask func(ctx context.Context)

type namedTask struct {
	name string
	fn   AsyncTask
}

type TaskRunner struct {
	mu    sync.Mutex
	tasks []namedTask
}

// Add 添加任务
func (tr *TaskRunner) Add(name string, task AsyncTask) {
	if task == nil {
		return
	}
	tr.mu.Lock()
	defer tr.mu.Unlock()
	tr.tasks = append(tr.tasks, namedTask{name: name, fn: task})
}

// RunAll 安全执行
func (tr *TaskRunner) RunAll() {
	tr.mu.Lock()
	todoTasks := tr.tasks
	tr.tasks = nil
	tr.mu.Unlock()

	for _, task := range todoTasks {
		t := task
		go func() {
			defer func() {
				if r := recover(); r != nil {
					// 使用全局 Zap 记录结构化日志
					// 这里的 global.Logger 替换为你实际的全局变量名
					global.Logger.Error("异步任务异常崩溃",
						zap.String("task_name", t.name),
						zap.Any("panic_info", r),
						zap.String("stack", string(debug.Stack())),
					)
				}
			}()

			// 异步任务执行，设置独立的超时控制
			ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
			defer cancel()

			t.fn(ctx)
		}()
	}
}
