package usecase

import (
	"context"
	"testing"

	"haixun-backend/internal/model/job/domain/entity"
	"haixun-backend/internal/model/job/domain/enum"

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

func TestRetryRun_AllowsManualRetryWhenAttemptReachedMaxAttempts(t *testing.T) {
	ctx := context.Background()
	template := generateRewriteDraftTemplate()
	jobID := primitive.NewObjectID()
	runs := newMemoryRunRepo(&entity.Run{
		ID:           jobID,
		TemplateType: template.Type,
		Status:       enum.RunStatusFailed,
		WorkerType:   workerTypeGenerateRewriteDraft,
		Attempt:      1,
		MaxAttempts:  1,
		Progress: entity.RunProgress{
			Steps: []entity.StepProgress{{ID: "rewrite_draft_generate", Status: enum.StepStatusFailed}},
		},
	})
	queue := newMemoryQueueRepo()
	uc := testUseCaseFull(template, runs, nil, queue)

	updated, err := uc.RetryRun(ctx, jobID.Hex())
	if err != nil {
		t.Fatalf("RetryRun() error = %v", err)
	}
	if updated.Status != enum.RunStatusQueued && updated.Status != enum.RunStatusPending {
		t.Fatalf("status = %s, want queued or pending", updated.Status)
	}
	if updated.Attempt != 2 {
		t.Fatalf("attempt = %d, want 2", updated.Attempt)
	}
}
