package usecase

import (
	"context"
	"testing"

	"go.mongodb.org/mongo-driver/bson/primitive"
	"haixun-backend/internal/model/job/domain/entity"
	"haixun-backend/internal/model/job/domain/enum"
)

func TestEnqueueRun_DoesNotOverwriteRunningClaim(t *testing.T) {
	ctx := context.Background()
	template := expandGraphTemplate()
	queue := newMemoryQueueRepo()
	runs := newMemoryRunRepo(nil)
	uc := testUseCaseFull(template, runs, nil, queue).(*jobUseCase)

	id := primitive.NewObjectID()
	runs.run = &entity.Run{
		ID:           id,
		TemplateType: template.Type,
		Status:       enum.RunStatusRunning,
		WorkerType:   "go",
		LockedBy:     "worker-a",
	}

	pending := &entity.Run{
		ID:           id,
		TemplateType: template.Type,
		Status:       enum.RunStatusPending,
		WorkerType:   "go",
	}
	updated, err := uc.enqueueRun(ctx, pending)
	if err != nil {
		t.Fatalf("enqueueRun() error = %v", err)
	}
	if updated.Status != enum.RunStatusRunning {
		t.Fatalf("status = %s, want running", updated.Status)
	}
	if len(queue.queues["go"]) != 0 {
		t.Fatalf("queue = %v, want duplicate enqueue removed", queue.queues["go"])
	}
}
