package jobs_test

import (
	"context"
	"sync/atomic"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	"github.com/yan1h/agent-coding-workflow/internal/jobs"
)

func TestModule_DisabledIsNoOp(t *testing.T) {
	t.Parallel()
	var called atomic.Int32
	m := jobs.NewModule(
		jobs.Config{Enabled: false, Workers: 1, ShutdownGrace: time.Second,
			WorkspaceFetch: jobs.RunnerConfig{Enabled: true, Interval: 10 * time.Millisecond}},
		jobs.ModuleDeps{
			Repo:     nil,
			Handlers: map[jobs.JobType]jobs.Handler{},
			RunnerFns: map[string]jobs.RunnerFunc{
				"workspace_fetch": func(_ context.Context) { called.Add(1) },
			},
		})
	require.NotNil(t, m)
	ctx, cancel := context.WithCancel(context.Background())
	m.Start(ctx)
	time.Sleep(50 * time.Millisecond)
	cancel()
	m.Stop(context.Background())
	assert.Zero(t, called.Load(), "disabled module must not run any runner")
}

func TestModule_EnabledRunsRegisteredRunner(t *testing.T) {
	t.Parallel()
	var ticks atomic.Int32
	m := jobs.NewModule(
		jobs.Config{Enabled: true, Workers: 0, ShutdownGrace: time.Second,
			WorkspaceFetch: jobs.RunnerConfig{Enabled: true, Interval: 10 * time.Millisecond}},
		jobs.ModuleDeps{
			Repo:     nil,
			Handlers: map[jobs.JobType]jobs.Handler{},
			RunnerFns: map[string]jobs.RunnerFunc{
				"workspace_fetch": func(_ context.Context) { ticks.Add(1) },
			},
		})
	ctx, cancel := context.WithCancel(context.Background())
	m.Start(ctx)
	require.Eventually(t, func() bool { return ticks.Load() >= 1 }, 200*time.Millisecond, 5*time.Millisecond)
	cancel()
	m.Stop(context.Background())
	assert.GreaterOrEqual(t, ticks.Load(), int32(1))
}

func TestModule_UnknownRunnerNameDisabled(t *testing.T) {
	t.Parallel()
	var called atomic.Int32
	m := jobs.NewModule(
		jobs.Config{Enabled: true, Workers: 0, ShutdownGrace: time.Second},
		jobs.ModuleDeps{
			Repo:     nil,
			Handlers: map[jobs.JobType]jobs.Handler{},
			RunnerFns: map[string]jobs.RunnerFunc{
				"made_up_runner": func(_ context.Context) { called.Add(1) },
			},
		})
	ctx, cancel := context.WithCancel(context.Background())
	m.Start(ctx)
	time.Sleep(50 * time.Millisecond)
	cancel()
	m.Stop(context.Background())
	assert.Zero(t, called.Load(), "unknown runner name should default to disabled")
}

func TestModule_StopRespectsShutdownGrace(t *testing.T) {
	t.Parallel()
	m := jobs.NewModule(
		jobs.Config{Enabled: true, Workers: 0, ShutdownGrace: 50 * time.Millisecond,
			WorkspaceFetch: jobs.RunnerConfig{Enabled: true, Interval: 10 * time.Millisecond}},
		jobs.ModuleDeps{
			Repo:     nil,
			Handlers: map[jobs.JobType]jobs.Handler{},
			RunnerFns: map[string]jobs.RunnerFunc{
				"workspace_fetch": func(_ context.Context) {},
			},
		})
	ctx, cancel := context.WithCancel(context.Background())
	m.Start(ctx)
	cancel()
	start := time.Now()
	m.Stop(context.Background())
	elapsed := time.Since(start)
	assert.Less(t, elapsed, 500*time.Millisecond, "Stop should return promptly")
}
