package runner

import (
	"context"
	"io"
	"log/slog"
	"path/filepath"
	"testing"

	"gitlab.com/Timfa/bluegit/internal/store"
)

func TestHoldKeepsJobsQueued(t *testing.T) {
	dir := t.TempDir()
	s, err := store.Open(filepath.Join(dir, "b.db"), make([]byte, 32))
	if err != nil {
		t.Fatal(err)
	}
	defer s.Close()
	ctx := context.Background()
	tim, _ := s.UpsertUser(ctx, 1, "tim", "", false)
	repo, err := s.CreateRepo(ctx, "user", tim.ID, "app", "", "master", "public")
	if err != nil {
		t.Fatal(err)
	}
	id, err := s.CreatePipeline(ctx, repo.ID, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "refs/heads/master", "push", "tim", "x", []store.NewJob{{Name: "build", Stage: "build", Script: "true"}})
	if err != nil {
		t.Fatal(err)
	}
	held := 0
	r := &Runner{Store: s, Storage: dir, Docker: "/nonexistent/docker", GitBin: "git", Log: slog.New(slog.NewTextHandler(io.Discard, nil)),
		Hold: func(p store.Pipeline) bool { held++; return p.ID == id }}
	r.slots = make(chan struct{}, 1)
	r.Tick(ctx)
	jobs, _ := s.JobsByPipeline(ctx, id)
	if held == 0 || jobs[0].Status != "queued" {
		t.Fatalf("job niet vastgehouden: held=%d status=%s", held, jobs[0].Status)
	}
}
