package records

import (
	"context"
	"testing"

	"github.com/nexuscrm/shared/pkg/constants"
)

func TestRecycleBinRootDeleteLineageDoesNotLeakIntoUnrelatedNestedDelete(t *testing.T) {
	rootCtx := withRecycleBinRootDeleteLineage(context.Background(), "Parent__c", "parent-1")
	rootFields := recycleBinLineageFieldsFromContext(rootCtx)
	rootOperationID := stringValue(rootFields[constants.FieldSysRecycleBin_DeleteOperationID])
	if rootOperationID == "" {
		t.Fatal("root delete lineage missing operation id")
	}

	nestedCtx := withRecycleBinRootDeleteLineage(rootCtx, "Other__c", "other-1")
	nestedFields := recycleBinLineageFieldsFromContext(nestedCtx)
	if got := stringValue(nestedFields[constants.FieldSysRecycleBin_DeleteOperationID]); got == "" || got == rootOperationID {
		t.Fatalf("nested unrelated delete operation id = %q, want fresh non-root operation", got)
	}
	if got := stringValue(nestedFields[constants.FieldSysRecycleBin_DeleteRootObjectAPIName]); got != "Other__c" {
		t.Fatalf("nested unrelated root object = %q, want Other__c", got)
	}
	if got := stringValue(nestedFields[constants.FieldSysRecycleBin_CascadeParentObjectAPIName]); got != "" {
		t.Fatalf("nested unrelated cascade parent = %q, want empty", got)
	}
}

func TestRecycleBinCascadeDeleteLineageOnlyAppliesToPreparedChild(t *testing.T) {
	rootCtx := withRecycleBinRootDeleteLineage(context.Background(), "Parent__c", "parent-1")
	rootFields := recycleBinLineageFieldsFromContext(rootCtx)
	rootOperationID := stringValue(rootFields[constants.FieldSysRecycleBin_DeleteOperationID])

	cascadeCtx := withRecycleBinCascadeDeleteLineage(rootCtx, "Child__c", "child-1", "Parent__c", "parent-1", "Parent__c")
	childDeleteCtx := withRecycleBinRootDeleteLineage(cascadeCtx, "Child__c", "child-1")
	childFields := recycleBinLineageFieldsFromContext(childDeleteCtx)
	if got := stringValue(childFields[constants.FieldSysRecycleBin_DeleteOperationID]); got != rootOperationID {
		t.Fatalf("cascade child operation id = %q, want root operation %q", got, rootOperationID)
	}
	if got := stringValue(childFields[constants.FieldSysRecycleBin_CascadeParentObjectAPIName]); got != "Parent__c" {
		t.Fatalf("cascade child parent object = %q, want Parent__c", got)
	}

	unrelatedCtx := withRecycleBinRootDeleteLineage(cascadeCtx, "Other__c", "other-1")
	unrelatedFields := recycleBinLineageFieldsFromContext(unrelatedCtx)
	if got := stringValue(unrelatedFields[constants.FieldSysRecycleBin_DeleteOperationID]); got == "" || got == rootOperationID {
		t.Fatalf("unrelated delete from cascade context operation id = %q, want fresh operation", got)
	}
	if got := stringValue(unrelatedFields[constants.FieldSysRecycleBin_CascadeParentObjectAPIName]); got != "" {
		t.Fatalf("unrelated delete from cascade context parent object = %q, want empty", got)
	}
}
