package usecase

import (
	"context"
	"errors"
	"testing"

	"apps/backend/internal/module/scout/domain"
	"apps/backend/internal/module/scout/repository"
)

func TestStartRunGuardsQueuedRunningAndTerminal(t *testing.T) {
	ctx := context.Background()
	store := repository.NewMemory()
	run := domain.NewRun("progress", "job-progress", 7, domain.RunBrief{Intent: "市集"}, 1)
	if err := store.CreateRun(ctx, run); err != nil {
		t.Fatal(err)
	}
	svc := New(store)
	started, err := svc.StartRun(ctx, 7, run.ID, run.JobID)
	if err != nil || started.Status != domain.RunRunning {
		t.Fatalf("start=%+v err=%v", started, err)
	}
	retry, err := svc.StartRun(ctx, 7, run.ID, run.JobID)
	if err != nil || retry.Status != domain.RunRunning {
		t.Fatalf("idempotent retry=%+v err=%v", retry, err)
	}
	if err := svc.FailRun(ctx, 7, run.ID, "timeout"); err != nil {
		t.Fatal(err)
	}
	if _, err := svc.StartRun(ctx, 7, run.ID, run.JobID); !errors.Is(err, domain.ErrIllegalRunStatus) {
		t.Fatalf("terminal restart error=%v", err)
	}
}

func TestStartRunRejectsWrongJobBinding(t *testing.T) {
	store := repository.NewMemory()
	run := domain.NewRun("wrong-job", "job-a", 7, domain.RunBrief{Intent: "市集"}, 1)
	if err := store.CreateRun(context.Background(), run); err != nil {
		t.Fatal(err)
	}
	if _, err := New(store).StartRun(context.Background(), 7, run.ID, "job-b"); !errors.Is(err, domain.ErrIllegalRunStatus) {
		t.Fatalf("wrong binding error=%v", err)
	}
}
