package runtimeworker

import (
	"context"
	"strings"
	"testing"

	"github.com/nexuscrm/backend/internal/runtimeconfig"
	"github.com/nexuscrm/files"
	"github.com/nexuscrm/persistence"
)

func TestMetadataRepairFailsBeforeDatabaseWithoutScopeOrExactObservation(t *testing.T) {
	role := validWorkerRole("runtime.record-event-dispatch.v1")
	if err := RepairProduction(context.Background(), testWorkerSourceRevision, runtimeconfig.Worker{Role: role}, RepairRequest{}); err == nil ||
		!strings.Contains(err.Error(), "exact scope") {
		t.Fatalf("missing scope error=%v", err)
	}
	role.Schema = runtimeconfig.WorkerConfigSchemaV2
	setValidMetadataScope(&role)
	if err := RepairProduction(context.Background(), testWorkerSourceRevision, runtimeconfig.Worker{Role: role}, RepairRequest{
		Poison: persistence.RuntimePoisonRepair{RowID: "row"},
	}); err == nil || !strings.Contains(err.Error(), "exact row") {
		t.Fatalf("incomplete observation error=%v", err)
	}
}

func TestFileUploadRepairRequiresExactObservationBeforeDatabaseAccess(t *testing.T) {
	role := validWorkerRole(files.RuntimeFileUploadLifecycleWorkFamily)
	err := RepairProduction(
		context.Background(),
		testWorkerSourceRevision,
		runtimeconfig.Worker{Role: role},
		RepairRequest{Poison: persistence.RuntimePoisonRepair{RowID: "row"}},
	)
	if err == nil || !strings.Contains(err.Error(), "exact row") {
		t.Fatalf("incomplete file poison observation error=%v", err)
	}
}

func TestPlatformCommandRepairRequiresMetadataScopeAndExactObservation(t *testing.T) {
	role := validWorkerRole(persistence.RuntimePlatformCommandExecutionWorkFamily)
	if err := RepairProduction(
		context.Background(),
		testWorkerSourceRevision,
		runtimeconfig.Worker{Role: role},
		RepairRequest{},
	); err == nil || !strings.Contains(err.Error(), "exact scope") {
		t.Fatalf("missing command scope error=%v", err)
	}

	role.Schema = runtimeconfig.WorkerConfigSchemaV2
	setValidMetadataScope(&role)
	role.RuntimeCapabilityID = "runtime.commands.accept.v1"
	if err := RepairProduction(
		context.Background(),
		testWorkerSourceRevision,
		runtimeconfig.Worker{Role: role},
		RepairRequest{Poison: persistence.RuntimePoisonRepair{RowID: "row"}},
	); err == nil || !strings.Contains(err.Error(), "exact row") {
		t.Fatalf("incomplete command poison observation error=%v", err)
	}
}
