package usecase

import (
	"context"
	"testing"
	"time"

	"haixun-backend/internal/library/clock"
	"haixun-backend/internal/model/job/domain/entity"
	"haixun-backend/internal/model/job/domain/enum"
)

func TestRunMaintenance_RepairsQueuedWithActiveLock(t *testing.T) {
	ctx := context.Background()
	template := expandGraphTemplate()
	queue := newMemoryQueueRepo()
	runs := newMemoryRunRepo(nil)
	started := clock.Now().UnixNano()
	lockedUntil := clock.Now().Add(10 * time.Minute).UnixNano()
	runs.run = &entity.Run{
		TemplateType: template.Type,
		Status:       enum.RunStatusQueued,
		WorkerType:   "go",
		LockedBy:     "worker-a",
		StartedAt:    &started,
		LockedUntil:  &lockedUntil,
	}
	uc := testUseCaseFull(template, runs, nil, queue)

	result, err := uc.RunMaintenance(ctx)
	if err != nil {
		t.Fatalf("RunMaintenance() error = %v", err)
	}
	if result.RepairedStuckClaims != 1 {
		t.Fatalf("RepairedStuckClaims = %d, want 1", result.RepairedStuckClaims)
	}
	if runs.run.Status != enum.RunStatusRunning {
		t.Fatalf("status = %s, want running", runs.run.Status)
	}
}
