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"

	"go.mongodb.org/mongo-driver/bson/primitive"
)

func TestRefreshRunLock_ExtendsMongoLockedUntil(t *testing.T) {
	ctx := context.Background()
	template := demoTemplate()
	queue := newMemoryQueueRepo()
	runs := newMemoryRunRepo(nil)
	lockedUntil := clock.Now().Add(-time.Minute).UnixNano()
	runs.run = &entity.Run{
		ID:           primitive.NewObjectID(),
		TemplateType: template.Type,
		Status:       enum.RunStatusRunning,
		LockedBy:     "worker-a",
		LockedUntil:  &lockedUntil,
	}
	uc := testUseCaseFull(template, runs, nil, queue)

	if _, err := queue.TryLock(ctx, runs.run.ID.Hex(), "worker-a", 600); err != nil {
		t.Fatalf("TryLock() error = %v", err)
	}
	if err := uc.RefreshRunLock(ctx, runs.run.ID.Hex(), "worker-a", 600); err != nil {
		t.Fatalf("RefreshRunLock() error = %v", err)
	}
	if runs.run.LockedUntil == nil || *runs.run.LockedUntil <= clock.NowUnixNano() {
		t.Fatalf("locked_until = %v, want future timestamp", runs.run.LockedUntil)
	}
}
