package records

import (
	"context"
	"testing"

	"github.com/nexuscrm/automation/autonumber"
	eventFeature "github.com/nexuscrm/events"
	"github.com/nexuscrm/kernel/pkg/formula"
	"github.com/nexuscrm/kernel/pkg/ports"
	"github.com/nexuscrm/kernel/pkg/validation"
	metadataFeature "github.com/nexuscrm/metadata"
	"github.com/nexuscrm/permissions"
	infraPersistence "github.com/nexuscrm/persistence"
	"github.com/nexuscrm/shared/pkg/constants"
	"github.com/nexuscrm/shared/pkg/contract"
	"github.com/nexuscrm/shared/pkg/fieldprovenance"
	"github.com/nexuscrm/shared/pkg/models"
)

func newRollupBoundaryTestService(repo ports.RecordRepository, schemas ...*models.ObjectMetadata) *PersistenceService {
	metaRepo := &stubUpsertMetaRepo{schemas: schemas}
	metaSvc := metadataFeature.NewMetadataService(metaRepo, nil, nil)
	permSvc := permissions.NewPermissionService(&stubUpsertPermRepo{
		grantCreate: true,
		grantEdit:   true,
		grantDelete: true,
	}, metaSvc, nil)
	return &PersistenceService{
		repo:                repo,
		rollup:              noopRollupProcessor{},
		metadata:            metaSvc,
		permissions:         permSvc,
		eventBus:            &eventFeature.NoOpEventBus{},
		validator:           metadataFeature.NewValidationService(formula.NewEngine()),
		schemaValidator:     validation.NewSchemaValidator(),
		txManager:           inlineTxManager{},
		parentLaneAdmission: &fakeParentLaneAdmissionController{},
	}
}

type triggerSubMetaRepo struct {
	*stubUpsertMetaRepo
	exec infraPersistence.Executor
}

func (r *triggerSubMetaRepo) GetExecutor(context.Context) infraPersistence.Executor {
	return r.exec
}

func newRollupBoundaryTestServiceWithMetadataRepo(repo ports.RecordRepository, metaRepo ports.MetadataRepository) *PersistenceService {
	metaSvc := metadataFeature.NewMetadataService(metaRepo, nil, nil)
	permSvc := permissions.NewPermissionService(&stubUpsertPermRepo{
		grantCreate: true,
		grantEdit:   true,
		grantDelete: true,
	}, metaSvc, nil)
	return &PersistenceService{
		repo:                repo,
		rollup:              noopRollupProcessor{},
		metadata:            metaSvc,
		permissions:         permSvc,
		eventBus:            &eventFeature.NoOpEventBus{},
		validator:           metadataFeature.NewValidationService(formula.NewEngine()),
		schemaValidator:     validation.NewSchemaValidator(),
		txManager:           inlineTxManager{},
		parentLaneAdmission: &fakeParentLaneAdmissionController{},
	}
}

func rollupChildSchemaForBoundaryTest() *models.ObjectMetadata {
	schema := &models.ObjectMetadata{
		APIName:      "Task__c",
		SharingModel: constants.SharingModelPublicReadWrite,
		Fields: []models.FieldMetadata{
			{APIName: constants.FieldID, Type: constants.FieldTypeString, Createable: false, Updateable: false},
			{APIName: constants.FieldName, Type: constants.FieldTypeString, Createable: true, Updateable: true},
			{
				APIName:     "ProjectId__c",
				Type:        constants.FieldTypeReference,
				ReferenceTo: []string{"Project__c"},
				Createable:  true,
				Updateable:  true,
			},
			{APIName: "Budget__c", Type: constants.FieldTypeDouble, Createable: true, Updateable: true},
			{APIName: "ExternalId__c", Type: constants.FieldTypeString, IsUnique: true, Createable: true, Updateable: true},
			{APIName: constants.FieldIsDeleted, Type: constants.FieldTypeBoolean, Createable: false, Updateable: false},
		},
	}
	makeFieldsMap(schema)
	return schema
}

func nonRollupSchemaForBoundaryTest() *models.ObjectMetadata {
	schema := &models.ObjectMetadata{
		APIName:      "Note__c",
		SharingModel: constants.SharingModelPublicReadWrite,
		Fields: []models.FieldMetadata{
			{APIName: constants.FieldID, Type: constants.FieldTypeString, Createable: false, Updateable: false},
			{APIName: constants.FieldName, Type: constants.FieldTypeString, Createable: true, Updateable: true},
		},
	}
	makeFieldsMap(schema)
	return schema
}

func flowSchemaForBoundaryTest() *models.ObjectMetadata {
	schema := &models.ObjectMetadata{
		APIName:      constants.TableFlow,
		TableType:    constants.TableType("system_automation"),
		SharingModel: constants.SharingModelPublicReadWrite,
		Fields: []models.FieldMetadata{
			{APIName: constants.FieldID, Type: constants.FieldTypeString, IsSystem: true},
			{APIName: constants.FieldIsDeleted, Type: constants.FieldTypeBoolean, IsSystem: true},
		},
	}
	makeFieldsMap(schema)
	return schema
}

func flowInterviewSchemaForBoundaryTest() *models.ObjectMetadata {
	schema := &models.ObjectMetadata{
		APIName:      constants.TableFlowInterview,
		TableType:    constants.TableType("system_automation"),
		SharingModel: constants.SharingModelPublicReadWrite,
		Fields: []models.FieldMetadata{
			{APIName: constants.FieldID, Type: constants.FieldTypeString, IsSystem: true},
			{
				APIName:     constants.FieldFlowInterview_FlowVersionID,
				Type:        constants.FieldTypeReference,
				ReferenceTo: []string{constants.TableFlow},
				Createable:  true,
				Updateable:  true,
			},
			{APIName: constants.FieldFlowInterview_InterviewLabel, Type: constants.FieldTypeString, Createable: true, Updateable: true},
			{APIName: constants.FieldFlowInterview_InterviewStatus, Type: constants.FieldTypeString, Createable: true, Updateable: true},
			{APIName: constants.FieldFlowInterview_CurrentElement, Type: constants.FieldTypeString, Createable: true, Updateable: true},
			{APIName: constants.FieldFlowInterview_ContextData, Type: constants.FieldTypeString, Createable: true, Updateable: true},
			{APIName: constants.FieldFlowInterview_PausedUntil, Type: constants.FieldTypeDatetime, Createable: true, Updateable: true},
			{APIName: constants.FieldIsDeleted, Type: constants.FieldTypeBoolean, IsSystem: true},
		},
	}
	makeFieldsMap(schema)
	return schema
}

type nestedRollupBoundaryRepo struct {
	captureRecordRepo
	oldByTable       map[string]models.SObject
	children         map[string][]models.SObject
	existsAnyByTable map[string]bool
}

func (r *nestedRollupBoundaryRepo) Exists(ctx context.Context, tableName string, id string) (bool, error) {
	if r.existsAnyByTable != nil && r.existsAnyByTable[tableName] {
		return true, nil
	}
	return r.captureRecordRepo.Exists(ctx, tableName, id)
}

func (r *nestedRollupBoundaryRepo) FindOne(ctx context.Context, tableName string, id string) (models.SObject, error) {
	if r.existsAnyByTable != nil && r.existsAnyByTable[tableName] {
		return models.SObject{constants.FieldID: id}, nil
	}
	if r.oldByTable != nil {
		if rec, ok := r.oldByTable[tableName]; ok {
			return cloneSObject(rec), nil
		}
	}
	return r.captureRecordRepo.FindOne(ctx, tableName, id)
}

func (r *nestedRollupBoundaryRepo) GetLock(ctx context.Context, tableName string, id string) (models.SObject, error) {
	if r.existsAnyByTable != nil && r.existsAnyByTable[tableName] {
		return models.SObject{constants.FieldID: id}, nil
	}
	if r.oldByTable != nil {
		if rec, ok := r.oldByTable[tableName]; ok {
			return cloneSObject(rec), nil
		}
	}
	return r.captureRecordRepo.GetLock(ctx, tableName, id)
}

func (r *nestedRollupBoundaryRepo) GetChildren(ctx context.Context, childTable string, foreignKey string, parentID string) ([]models.SObject, error) {
	key := childTable + "|" + foreignKey + "|" + parentID
	rows := r.children[key]
	return cloneSObjects(rows), nil
}

func (r *nestedRollupBoundaryRepo) MaxNumericFieldForParent(ctx context.Context, schema *models.ObjectMetadata, targetField, parentField string, parentValue interface{}) (float64, error) {
	return 0, nil
}

func defaultChildRowParentSchemaForBoundaryTest() *models.ObjectMetadata {
	schema := &models.ObjectMetadata{
		APIName:      "Grant__c",
		SharingModel: constants.SharingModelPublicReadWrite,
		Fields: []models.FieldMetadata{
			{APIName: constants.FieldID, Type: constants.FieldTypeString, Createable: false, Updateable: false},
			{APIName: constants.FieldName, Type: constants.FieldTypeString, Createable: true, Updateable: true},
		},
		DefaultChildRows: []models.DefaultChildRow{{
			TargetObject:      "Task__c",
			TargetLookupField: "GrantId__c",
			FieldValues:       models.SObject{constants.FieldName: "nested-task"},
		}},
	}
	makeFieldsMap(schema)
	return schema
}

func siblingMaxDefaultChildRowParentSchemaForBoundaryTest() *models.ObjectMetadata {
	schema := &models.ObjectMetadata{
		APIName:      "Parent__c",
		KeyPrefix:    runtimeStringPtr("a10"),
		SharingModel: constants.SharingModelPublicReadWrite,
		Fields: []models.FieldMetadata{
			{APIName: constants.FieldID, Type: constants.FieldTypeString, Createable: false, Updateable: false},
			{APIName: constants.FieldName, Type: constants.FieldTypeString, Createable: true, Updateable: true},
		},
		DefaultChildRows: []models.DefaultChildRow{{
			TargetObject:      "LineItem__c",
			TargetLookupField: "ParentId",
		}},
	}
	makeFieldsMap(schema)
	return schema
}

func childCloneParentSchemaForBoundaryTest() *models.ObjectMetadata {
	schema := &models.ObjectMetadata{
		APIName:      "Quote__c",
		KeyPrefix:    runtimeStringPtr("0Q0"),
		SharingModel: constants.SharingModelPublicReadWrite,
		Fields: []models.FieldMetadata{
			{APIName: constants.FieldID, Type: constants.FieldTypeString, Createable: false, Updateable: false},
			{APIName: constants.FieldName, Type: constants.FieldTypeString, Createable: true, Updateable: true},
			{APIName: "SourceQuoteId__c", Type: constants.FieldTypeString, Createable: true, Updateable: true},
			{APIName: constants.FieldIsDeleted, Type: constants.FieldTypeBoolean, Createable: false, Updateable: false},
		},
		ChildCloneRules: []models.ChildCloneRule{{
			ParentLookupField: "SourceQuoteId__c",
			SourceObject:      "TemplateTask__c",
			SourceLookupField: "QuoteId__c",
			TargetObject:      "Task__c",
			TargetLookupField: "QuoteId__c",
			FieldMappings:     map[string]string{constants.FieldName: constants.FieldName},
		}},
	}
	makeFieldsMap(schema)
	return schema
}

func childCloneParentSchemaWithDefaultedSourceLookupForBoundaryTest() *models.ObjectMetadata {
	schema := childCloneParentSchemaForBoundaryTest()
	defaultSource := "source-quote-001"
	for i := range schema.Fields {
		if schema.Fields[i].APIName == "SourceQuoteId__c" {
			schema.Fields[i].DefaultValue = &defaultSource
		}
	}
	makeFieldsMap(schema)
	return schema
}

func hydratedChildCloneRootSchemaForBoundaryTest() *models.ObjectMetadata {
	schema := &models.ObjectMetadata{
		APIName:      "Bundle__c",
		SharingModel: constants.SharingModelPublicReadWrite,
		Fields: []models.FieldMetadata{
			{APIName: constants.FieldID, Type: constants.FieldTypeString, Createable: false, Updateable: false},
			{APIName: constants.FieldName, Type: constants.FieldTypeString, Createable: true, Updateable: true},
			{APIName: "SourceBundleId__c", Type: constants.FieldTypeString, Createable: true, Updateable: true},
		},
		ChildCloneRules: []models.ChildCloneRule{{
			ParentLookupField: "SourceBundleId__c",
			SourceObject:      "TemplateQuote__c",
			SourceLookupField: "BundleId__c",
			TargetObject:      "Quote__c",
			TargetLookupField: "BundleId__c",
			FieldMappings:     map[string]string{"SourceQuoteId__c": "ParentQuoteId__c"},
			HydrateSource:     true,
		}},
	}
	makeFieldsMap(schema)
	return schema
}

func cascadeRootSchemaForBoundaryTest() *models.ObjectMetadata {
	schema := &models.ObjectMetadata{
		APIName:      "Program__c",
		SharingModel: constants.SharingModelPublicReadWrite,
		Fields: []models.FieldMetadata{
			{APIName: constants.FieldID, Type: constants.FieldTypeString, Createable: false, Updateable: false},
			{APIName: constants.FieldName, Type: constants.FieldTypeString, Createable: true, Updateable: true},
			{APIName: constants.FieldIsDeleted, Type: constants.FieldTypeBoolean, Createable: false, Updateable: false},
		},
	}
	makeFieldsMap(schema)
	return schema
}

func siblingDefaultChildRowsRootSchemaForBoundaryTest() *models.ObjectMetadata {
	schema := &models.ObjectMetadata{
		APIName:      "Bundle__c",
		SharingModel: constants.SharingModelPublicReadWrite,
		Fields: []models.FieldMetadata{
			{APIName: constants.FieldID, Type: constants.FieldTypeString, Createable: false, Updateable: false},
			{APIName: constants.FieldName, Type: constants.FieldTypeString, Createable: true, Updateable: true},
		},
		DefaultChildRows: []models.DefaultChildRow{
			{
				TargetObject:      "Quote__c",
				TargetLookupField: "BundleId__c",
				FieldValues:       models.SObject{constants.FieldName: "Quote without source"},
			},
			{
				TargetObject:      "Quote__c",
				TargetLookupField: "BundleId__c",
				FieldValues: models.SObject{
					constants.FieldName: "Quote with source",
					"SourceQuoteId__c":  "source-quote-001",
				},
			},
		},
	}
	makeFieldsMap(schema)
	return schema
}

func templateTaskSchemaForBoundaryTest() *models.ObjectMetadata {
	schema := &models.ObjectMetadata{
		APIName:      "TemplateTask__c",
		SharingModel: constants.SharingModelPublicReadWrite,
		Fields: []models.FieldMetadata{
			{APIName: constants.FieldID, Type: constants.FieldTypeString, Createable: false, Updateable: false},
			{APIName: constants.FieldName, Type: constants.FieldTypeString, Createable: true, Updateable: true},
			{
				APIName:     "QuoteId__c",
				Type:        constants.FieldTypeReference,
				ReferenceTo: []string{"Quote__c"},
				Createable:  true,
				Updateable:  true,
			},
		},
	}
	makeFieldsMap(schema)
	return schema
}

func templateQuoteSchemaForBoundaryTest() *models.ObjectMetadata {
	schema := &models.ObjectMetadata{
		APIName:      "TemplateQuote__c",
		SharingModel: constants.SharingModelPublicReadWrite,
		Fields: []models.FieldMetadata{
			{APIName: constants.FieldID, Type: constants.FieldTypeString, Createable: false, Updateable: false},
			{APIName: constants.FieldName, Type: constants.FieldTypeString, Createable: true, Updateable: true},
			{APIName: "BundleId__c", Type: constants.FieldTypeString, Createable: true, Updateable: true},
			{APIName: "ParentQuoteId__c", Type: constants.FieldTypeString, Createable: true, Updateable: true},
		},
	}
	makeFieldsMap(schema)
	return schema
}

func rollupChildSchemaWithAdditionalParentsForBoundaryTest() *models.ObjectMetadata {
	schema := rollupChildSchemaForBoundaryTest()
	schema.Fields = append(schema.Fields, models.FieldMetadata{
		APIName:     "GrantId__c",
		Type:        constants.FieldTypeReference,
		ReferenceTo: []string{"Grant__c"},
		Createable:  true,
		Updateable:  true,
	})
	schema.Fields = append(schema.Fields, models.FieldMetadata{
		APIName:        "QuoteId__c",
		Type:           constants.FieldTypeReference,
		ReferenceTo:    []string{"Quote__c"},
		Createable:     true,
		Updateable:     true,
		DeleteRule:     deleteRulePtr(constants.DeleteRuleCascade),
		IsMasterDetail: false,
	})
	makeFieldsMap(schema)
	return schema
}

func deleteRulePtr(rule constants.DeleteRule) *constants.DeleteRule {
	return &rule
}

func runtimeStringPtr(v string) *string {
	return &v
}

func assertBulkOptimisticOnly(t *testing.T, txm *recordingBulkTxManager) {
	t.Helper()
	if txm.optimisticCalls != 1 {
		t.Fatalf("optimistic transaction calls = %d, want 1", txm.optimisticCalls)
	}
	if txm.pessimisticCalls != 0 {
		t.Fatalf("pessimistic transaction calls = %d, want 0", txm.pessimisticCalls)
	}
}

func TestInsertRollupChildUsesPessimisticTransactionAtRoot(t *testing.T) {
	repo := &captureRecordRepo{}
	ps := newRollupBoundaryTestService(repo, parentWithRollupSchemaForBulk(), rollupChildSchemaForBoundaryTest())
	txm := &recordingBulkTxManager{}
	ps.txManager = txm
	ctx := constants.WithSecurityContext(context.Background(), constants.SystemContext, "rollup tx boundary insert root")

	_, err := ps.Insert(ctx, "Task__c", models.SObject{
		constants.FieldName: "Task A",
		"Budget__c":         float64(10),
	}, recordEntrypointUser())
	if err != nil {
		t.Fatalf("Insert: %v", err)
	}
	assertBulkPessimisticOnly(t, txm)
}

func TestInsertSiblingMaxDefaultChildUsesPessimisticTransactionAtRoot(t *testing.T) {
	repo := &siblingMaxCaptureRepo{
		captureRecordRepo: captureRecordRepo{
			exists: map[string]map[string]bool{"Parent__c": {"parent-001": true}},
			old:    models.SObject{constants.FieldID: "parent-001"},
		},
	}
	ps := newRollupBoundaryTestService(repo, siblingMaxTestSchema(t))
	txm := &recordingBulkTxManager{}
	ps.txManager = txm
	ctx := constants.WithSecurityContext(context.Background(), constants.SystemContext, "sibling max tx boundary insert root")

	_, err := ps.Insert(ctx, "LineItem__c", models.SObject{
		"ParentId": "parent-001",
	}, recordEntrypointUser())
	if err != nil {
		t.Fatalf("Insert: %v", err)
	}
	assertBulkPessimisticOnly(t, txm)
	if repo.inserted["SortOrder__c"] != int64(1) {
		t.Fatalf("inserted SortOrder__c = %#v, want int64(1)", repo.inserted["SortOrder__c"])
	}
}

func TestInsertRollupChildUsesPessimisticTransactionAtRootWithLowercaseObjectName(t *testing.T) {
	repo := &captureRecordRepo{}
	ps := newRollupBoundaryTestService(repo, parentWithRollupSchemaForBulk(), rollupChildSchemaForBoundaryTest())
	txm := &recordingBulkTxManager{}
	ps.txManager = txm
	ctx := constants.WithSecurityContext(context.Background(), constants.SystemContext, "rollup tx boundary insert root lowercase")

	_, err := ps.Insert(ctx, "task__c", models.SObject{
		constants.FieldName: "Task A",
		"Budget__c":         float64(10),
	}, recordEntrypointUser())
	if err != nil {
		t.Fatalf("Insert: %v", err)
	}
	assertBulkPessimisticOnly(t, txm)
}

func TestInsertNonRollupObjectUsesOptimisticTransactionAtRoot(t *testing.T) {
	repo := &captureRecordRepo{}
	ps := newRollupBoundaryTestService(repo, nonRollupSchemaForBoundaryTest())
	txm := &recordingBulkTxManager{}
	ps.txManager = txm

	_, err := ps.Insert(context.Background(), "Note__c", models.SObject{
		constants.FieldName: "Note A",
	}, recordEntrypointUser())
	if err != nil {
		t.Fatalf("Insert: %v", err)
	}
	assertBulkOptimisticOnly(t, txm)
}

func TestInsertRollupChildFailsClosedInsideActivePlainTransaction(t *testing.T) {
	repo := &captureRecordRepo{}
	ps := newRollupBoundaryTestService(repo, parentWithRollupSchemaForBulk(), rollupChildSchemaForBoundaryTest())
	txm := &recordingBulkTxManager{}
	ps.txManager = txm
	ctx := constants.WithSecurityContext(context.Background(), constants.SystemContext, "rollup tx boundary insert nested")

	err := ps.RunInTransaction(ctx, func(txCtx context.Context) error {
		_, err := ps.Insert(txCtx, "Task__c", models.SObject{
			constants.FieldName: "Task A",
			"Budget__c":         float64(10),
		}, recordEntrypointUser())
		return err
	})
	if err == nil {
		t.Fatal("RunInTransaction/Insert = nil, want fail-closed error")
	}
	if txm.optimisticCalls != 1 {
		t.Fatalf("optimistic transaction calls = %d, want 1 outer call", txm.optimisticCalls)
	}
	if txm.pessimisticCalls != 0 {
		t.Fatalf("pessimistic transaction calls = %d, want 0 on fail-closed path", txm.pessimisticCalls)
	}
	if repo.inserted != nil {
		t.Fatalf("repo.Insert was called with %#v, want fail-closed before nested rollup-child write", repo.inserted)
	}
}

func TestInsertNonRollupObjectReusesActivePlainTransaction(t *testing.T) {
	repo := &captureRecordRepo{}
	ps := newRollupBoundaryTestService(repo, nonRollupSchemaForBoundaryTest())
	txm := &recordingBulkTxManager{}
	ps.txManager = txm

	err := ps.RunInTransaction(context.Background(), func(txCtx context.Context) error {
		_, err := ps.Insert(txCtx, "Note__c", models.SObject{
			constants.FieldName: "Note A",
		}, recordEntrypointUser())
		return err
	})
	if err != nil {
		t.Fatalf("RunInTransaction/Insert: %v", err)
	}
	assertBulkOptimisticOnly(t, txm)
}

func TestInsertLookupWriteFailsClosedInsideActivePlainTransaction(t *testing.T) {
	parent := relationshipDeleteParentSchema()
	child := relationshipDeleteChildSchema(models.FieldMetadata{
		APIName:     "ParentId__c",
		Type:        constants.FieldTypeReference,
		ReferenceTo: []string{"Parent__c"},
		Createable:  true,
		Updateable:  true,
	})
	repo := &captureRecordRepo{}
	ps := newRollupBoundaryTestService(repo, parent, child)
	txm := &recordingBulkTxManager{}
	ps.txManager = txm

	err := ps.RunInTransaction(context.Background(), func(txCtx context.Context) error {
		_, err := ps.Insert(txCtx, "Child__c", models.SObject{
			constants.FieldName: "Child A",
			"ParentId__c":       "parent-001",
		}, recordEntrypointUser())
		return err
	})
	if err == nil {
		t.Fatal("RunInTransaction/lookup Insert = nil, want fail-closed nested pessimistic boundary error")
	}
	if txm.optimisticCalls != 1 {
		t.Fatalf("optimistic transaction calls = %d, want 1 outer call", txm.optimisticCalls)
	}
	if txm.pessimisticCalls != 0 {
		t.Fatalf("pessimistic transaction calls = %d, want 0 on fail-closed path", txm.pessimisticCalls)
	}
	if repo.inserted != nil {
		t.Fatalf("repo.Insert was called with %#v, want fail-closed before nested lookup write", repo.inserted)
	}
}

func TestInsertSystemAutomationLookupObjectReusesActivePlainTransaction(t *testing.T) {
	repo := &captureRecordRepo{
		old: models.SObject{
			constants.FieldID:        "flow-001",
			constants.FieldIsDeleted: false,
		},
	}
	ps := newRollupBoundaryTestService(repo, flowSchemaForBoundaryTest(), flowInterviewSchemaForBoundaryTest())
	txm := &recordingBulkTxManager{}
	ps.txManager = txm

	err := ps.RunInTransaction(context.Background(), func(txCtx context.Context) error {
		writeCtx := constants.WithSecurityContext(txCtx, constants.SystemContext, "flow interview pause bookkeeping write")
		_, err := ps.Insert(writeCtx, constants.TableFlowInterview, models.SObject{
			constants.FieldFlowInterview_FlowVersionID:   "flow-001",
			constants.FieldFlowInterview_InterviewLabel:  "Paused interview",
			constants.FieldFlowInterview_InterviewStatus: models.FlowInterviewStatusPaused,
			constants.FieldFlowInterview_CurrentElement:  "Wait_1",
			constants.FieldFlowInterview_ContextData:     "{}",
		}, recordEntrypointUser())
		return err
	})
	if err != nil {
		t.Fatalf("RunInTransaction/FlowInterview Insert: %v", err)
	}
	assertBulkOptimisticOnly(t, txm)
	if repo.inserted == nil {
		t.Fatal("FlowInterview insert did not reach repo.Insert")
	}
}

func TestUpdateSystemAutomationLookupObjectReusesActivePlainTransaction(t *testing.T) {
	repo := &captureRecordRepo{
		old: models.SObject{
			constants.FieldID:                            "fi-001",
			constants.FieldFlowInterview_FlowVersionID:   "flow-001",
			constants.FieldFlowInterview_InterviewLabel:  "Paused interview",
			constants.FieldFlowInterview_InterviewStatus: models.FlowInterviewStatusRunning,
			constants.FieldFlowInterview_CurrentElement:  "Start",
			constants.FieldFlowInterview_ContextData:     "{}",
			constants.FieldIsDeleted:                     false,
		},
	}
	ps := newRollupBoundaryTestService(repo, flowSchemaForBoundaryTest(), flowInterviewSchemaForBoundaryTest())
	txm := &recordingBulkTxManager{}
	ps.txManager = txm

	err := ps.RunInTransaction(context.Background(), func(txCtx context.Context) error {
		writeCtx := constants.WithSecurityContext(txCtx, constants.SystemContext, "flow interview pause bookkeeping write")
		return ps.Update(writeCtx, constants.TableFlowInterview, "fi-001", models.SObject{
			constants.FieldFlowInterview_InterviewStatus: models.FlowInterviewStatusPaused,
			constants.FieldFlowInterview_CurrentElement:  "Wait_1",
			constants.FieldFlowInterview_ContextData:     "{}",
		}, recordEntrypointUser())
	})
	if err != nil {
		t.Fatalf("RunInTransaction/FlowInterview Update: %v", err)
	}
	assertBulkOptimisticOnly(t, txm)
	if repo.updated == nil {
		t.Fatal("FlowInterview update did not reach repo.Update")
	}
}

func TestUpdateLookupWriteFailsClosedInsideActivePlainTransaction(t *testing.T) {
	parent := relationshipDeleteParentSchema()
	child := relationshipDeleteChildSchema(models.FieldMetadata{
		APIName:     "ParentId__c",
		Type:        constants.FieldTypeReference,
		ReferenceTo: []string{"Parent__c"},
		Createable:  true,
		Updateable:  true,
	})
	repo := &captureRecordRepo{
		old: models.SObject{
			constants.FieldID:        "child-001",
			constants.FieldName:      "Child A",
			"ParentId__c":            "parent-old",
			constants.FieldIsDeleted: false,
		},
	}
	ps := newRollupBoundaryTestService(repo, parent, child)
	txm := &recordingBulkTxManager{}
	ps.txManager = txm

	err := ps.RunInTransaction(context.Background(), func(txCtx context.Context) error {
		return ps.Update(txCtx, "Child__c", "child-001", models.SObject{
			"ParentId__c": "parent-new",
		}, recordEntrypointUser())
	})
	if err == nil {
		t.Fatal("RunInTransaction/lookup Update = nil, want fail-closed nested pessimistic boundary error")
	}
	if txm.optimisticCalls != 1 {
		t.Fatalf("optimistic transaction calls = %d, want 1 outer call", txm.optimisticCalls)
	}
	if txm.pessimisticCalls != 0 {
		t.Fatalf("pessimistic transaction calls = %d, want 0 on fail-closed path", txm.pessimisticCalls)
	}
	if repo.updated != nil {
		t.Fatalf("repo.Update was called with %#v, want fail-closed before nested lookup write", repo.updated)
	}
}

func TestUpdateRollupChildUsesPessimisticTransactionAtRoot(t *testing.T) {
	repo := &captureRecordRepo{
		old: models.SObject{
			constants.FieldID:   "tsk-001",
			constants.FieldName: "Task A",
			"ProjectId__c":      "proj-001",
			"Budget__c":         float64(10),
		},
	}
	ps := newRollupBoundaryTestService(repo, parentWithRollupSchemaForBulk(), rollupChildSchemaForBoundaryTest())
	txm := &recordingBulkTxManager{}
	ps.txManager = txm

	err := ps.Update(context.Background(), "Task__c", "tsk-001", models.SObject{
		"Budget__c": float64(20),
	}, recordEntrypointUser())
	if err != nil {
		t.Fatalf("Update: %v", err)
	}
	assertBulkPessimisticOnly(t, txm)
}

func TestDeleteRollupChildUsesPessimisticTransactionAtRoot(t *testing.T) {
	repo := &captureRecordRepo{
		old: models.SObject{
			constants.FieldID:        "tsk-001",
			constants.FieldName:      "Task A",
			"ProjectId__c":           "proj-001",
			"Budget__c":              float64(10),
			constants.FieldIsDeleted: 0,
		},
	}
	ps := newRollupBoundaryTestService(repo, parentWithRollupSchemaForBulk(), rollupChildSchemaForBoundaryTest())
	txm := &recordingBulkTxManager{}
	ps.txManager = txm

	err := ps.Delete(context.Background(), "Task__c", "tsk-001", recordEntrypointUser())
	if err != nil {
		t.Fatalf("Delete: %v", err)
	}
	assertBulkPessimisticOnly(t, txm)
}

func TestUpsertByExternalIDRollupChildUsesPessimisticTransactionAtRoot(t *testing.T) {
	repo := &captureRecordRepo{}
	ps := newRollupBoundaryTestService(repo, parentWithRollupSchemaForBulk(), rollupChildSchemaForBoundaryTest())
	txm := &recordingBulkTxManager{}
	ps.txManager = txm
	ctx := constants.WithSecurityContext(context.Background(), constants.SystemContext, "rollup tx boundary upsert root")

	_, _, err := ps.UpsertByExternalID(ctx, "Task__c", "ExternalId__c", "ext-001", models.SObject{
		constants.FieldName: "Task A",
		"Budget__c":         float64(10),
	}, recordEntrypointUser())
	if err != nil {
		t.Fatalf("UpsertByExternalID: %v", err)
	}
	assertBulkPessimisticOnly(t, txm)
}

func TestBulkInsertRollupChildUsesPessimisticTransactionAtRoot(t *testing.T) {
	parentSchema := parentWithRollupSchemaForBulk()
	childSchema := rollupChildSchemaForBoundaryTest()
	repo := &bulkInsertRollupRepoForBulk{}
	rollupCapture := &capturingBulkRollupProcessor{}
	ps := newBulkInsertRollupTestService(parentSchema, childSchema, repo, rollupCapture)
	txm := &recordingBulkTxManager{}
	ps.txManager = txm

	_, err := ps.BulkInsert(context.Background(), "Task__c", []models.SObject{
		{constants.FieldName: "Task A", "ProjectId__c": "proj-001", "Budget__c": float64(10)},
		{constants.FieldName: "Task B", "ProjectId__c": "proj-001", "Budget__c": float64(20)},
	}, recordEntrypointUser(), BulkInsertOptions{})
	if err != nil {
		t.Fatalf("BulkInsert: %v", err)
	}
	if len(rollupCapture.bulkCalls) == 0 {
		t.Fatal("ProcessBulkRollups was not called")
	}
	assertBulkPessimisticOnly(t, txm)
}

func TestRollupMutationRequiresPessimisticBoundary_InsertViaDefaultChildRows(t *testing.T) {
	allSchemas := []*models.ObjectMetadata{
		parentWithRollupSchemaForBulk(),
		rollupChildSchemaWithAdditionalParentsForBoundaryTest(),
		defaultChildRowParentSchemaForBoundaryTest(),
	}
	if !rollupMutationRequiresPessimisticBoundaryForSchemas(allSchemas, "Grant__c", rollupMutationOperationInsert) {
		t.Fatal("rollupMutationRequiresPessimisticBoundaryForSchemas(insert/default child rows) = false, want true")
	}
}

func TestRollupMutationRequiresPessimisticBoundary_InsertViaSiblingMaxDefaultChildRows(t *testing.T) {
	allSchemas := []*models.ObjectMetadata{
		siblingMaxDefaultChildRowParentSchemaForBoundaryTest(),
		siblingMaxTestSchema(t),
	}
	if !rollupMutationRequiresPessimisticBoundaryForSchemas(allSchemas, "Parent__c", rollupMutationOperationInsert) {
		t.Fatal("rollupMutationRequiresPessimisticBoundaryForSchemas(insert/sibling max default child rows) = false, want true")
	}
}

func TestRollupMutationRequiresPessimisticBoundary_InsertViaChildCloneRules(t *testing.T) {
	allSchemas := []*models.ObjectMetadata{
		parentWithRollupSchemaForBulk(),
		rollupChildSchemaWithAdditionalParentsForBoundaryTest(),
		childCloneParentSchemaForBoundaryTest(),
		templateTaskSchemaForBoundaryTest(),
	}
	if rollupMutationRequiresPessimisticBoundaryForSchemas(allSchemas, "Quote__c", rollupMutationOperationInsert) {
		t.Fatal("rollupMutationRequiresPessimisticBoundaryForSchemas(insert/child clone) = true, want false without row-level evidence")
	}
}

func TestRollupMutationRequiresPessimisticBoundary_DeleteViaCascadeChildren(t *testing.T) {
	allSchemas := []*models.ObjectMetadata{
		parentWithRollupSchemaForBulk(),
		rollupChildSchemaWithAdditionalParentsForBoundaryTest(),
		childCloneParentSchemaForBoundaryTest(),
	}
	if rollupMutationRequiresPessimisticBoundaryForSchemas(allSchemas, "Quote__c", rollupMutationOperationDelete) {
		t.Fatal("rollupMutationRequiresPessimisticBoundaryForSchemas(delete/cascade child) = true, want false without row-level evidence")
	}
}

func TestInsertNonRollupParentWithDefaultChildRowsUsesPessimisticTransaction(t *testing.T) {
	repo := &nestedRollupBoundaryRepo{
		existsAnyByTable: map[string]bool{"Grant__c": true},
		oldByTable: map[string]models.SObject{
			"Grant__c": {constants.FieldID: "grant-parent"},
		},
	}
	ps := newRollupBoundaryTestService(
		repo,
		parentWithRollupSchemaForBulk(),
		rollupChildSchemaWithAdditionalParentsForBoundaryTest(),
		defaultChildRowParentSchemaForBoundaryTest(),
	)
	txm := &recordingBulkTxManager{}
	ps.txManager = txm
	ctx := constants.WithSecurityContext(context.Background(), constants.SystemContext, "default child rows root insert")

	_, err := ps.Insert(ctx, "Grant__c", models.SObject{
		constants.FieldName: "Grant A",
	}, recordEntrypointUser())
	if err != nil {
		t.Fatalf("Insert: %v", err)
	}
	assertBulkPessimisticOnly(t, txm)
}

func TestInsertNonRollupParentWithSiblingMaxDefaultChildRowsUsesPessimisticTransaction(t *testing.T) {
	repo := &nestedRollupBoundaryRepo{
		existsAnyByTable: map[string]bool{"Parent__c": true},
		oldByTable: map[string]models.SObject{
			"Parent__c": {constants.FieldID: "parent-001"},
		},
	}
	ps := newRollupBoundaryTestService(
		repo,
		siblingMaxDefaultChildRowParentSchemaForBoundaryTest(),
		siblingMaxTestSchema(t),
	)
	txm := &recordingBulkTxManager{}
	ps.txManager = txm
	ctx := constants.WithSecurityContext(context.Background(), constants.SystemContext, "sibling max default child rows root insert")

	_, err := ps.Insert(ctx, "Parent__c", models.SObject{
		constants.FieldName: "Parent A",
	}, recordEntrypointUser())
	if err != nil {
		t.Fatalf("Insert: %v", err)
	}
	assertBulkPessimisticOnly(t, txm)
}

func TestInsertNonRollupParentWithChildCloneRulesUsesPessimisticTransaction(t *testing.T) {
	repo := &nestedRollupBoundaryRepo{
		children: map[string][]models.SObject{
			"TemplateTask__c|QuoteId__c|source-quote-001": {
				{constants.FieldID: "tmpl-1", constants.FieldName: "Template task"},
			},
		},
		existsAnyByTable: map[string]bool{"Quote__c": true, "Bundle__c": true},
		oldByTable: map[string]models.SObject{
			"Quote__c":  {constants.FieldID: "quote-parent"},
			"Bundle__c": {constants.FieldID: "bundle-parent"},
		},
	}
	ps := newRollupBoundaryTestService(
		repo,
		parentWithRollupSchemaForBulk(),
		rollupChildSchemaWithAdditionalParentsForBoundaryTest(),
		childCloneParentSchemaForBoundaryTest(),
		templateTaskSchemaForBoundaryTest(),
	)
	txm := &recordingBulkTxManager{}
	ps.txManager = txm
	ctx := constants.WithSecurityContext(context.Background(), constants.SystemContext, "child clone root insert")

	_, err := ps.Insert(ctx, "Quote__c", models.SObject{
		constants.FieldName: "Quote A",
		"SourceQuoteId__c":  "source-quote-001",
	}, recordEntrypointUser())
	if err != nil {
		t.Fatalf("Insert: %v", err)
	}
	assertBulkPessimisticOnly(t, txm)
}

func TestChildCloneLifecyclePessimisticRequirementPreservesCallerSuppression(t *testing.T) {
	const capability = "test.clone-target.requires-pessimistic"
	target := rollupChildSchemaForBoundaryTest()
	target.AccessPolicy = &models.ObjectAccessPolicy{Lifecycle: &models.RecordLifecycleAccessPolicy{
		Hooks: []models.RecordLifecycleHookPolicy{{
			Phase: string(contract.RecordLifecycleAfterCreateInTx), Capability: capability,
		}},
	}}
	parent := childCloneParentSchemaWithDefaultedSourceLookupForBoundaryTest()
	parent.KeyPrefix = nil
	ps := newRollupBoundaryTestService(
		&nestedRollupBoundaryRepo{},
		parent,
		target,
		templateTaskSchemaForBoundaryTest(),
	)
	if err := ps.RegisterRecordLifecycleHook(contract.RecordLifecycleRegistration{
		Capability:                     capability,
		Phase:                          contract.RecordLifecycleAfterCreateInTx,
		RequiresPessimisticTransaction: true,
		Hook:                           func(context.Context, contract.RecordLifecycleEvent) error { return nil },
	}); err != nil {
		t.Fatalf("RegisterRecordLifecycleHook: %v", err)
	}

	requires, reason := ps.rollupInsertPessimisticBoundaryDecision(context.Background(), "Quote__c", models.SObject{constants.FieldName: "Quote A"})
	if !requires || reason != "metadata_owned_clone_mutation_risk" {
		t.Fatalf("unsuppressed clone boundary = %v/%s, want true/metadata_owned_clone_mutation_risk", requires, reason)
	}
	suppressed := contract.WithRecordLifecycleHooksSuppressed(context.Background())
	requires, reason = ps.rollupInsertPessimisticBoundaryDecision(suppressed, "Quote__c", models.SObject{constants.FieldName: "Quote A"})
	if requires || reason != "none" {
		t.Fatalf("suppressed clone boundary = %v/%s, want false/none", requires, reason)
	}
}

func TestInsertNonRollupParentWithChildCloneRulesUsesPessimisticTransactionWithoutCurrentSourceRows(t *testing.T) {
	repo := &nestedRollupBoundaryRepo{
		existsAnyByTable: map[string]bool{"Quote__c": true},
		oldByTable: map[string]models.SObject{
			"Quote__c": {constants.FieldID: "quote-parent"},
		},
	}
	ps := newRollupBoundaryTestService(
		repo,
		parentWithRollupSchemaForBulk(),
		rollupChildSchemaWithAdditionalParentsForBoundaryTest(),
		childCloneParentSchemaForBoundaryTest(),
		templateTaskSchemaForBoundaryTest(),
	)
	txm := &recordingBulkTxManager{}
	ps.txManager = txm
	ctx := constants.WithSecurityContext(context.Background(), constants.SystemContext, "child clone root insert without current rows")

	_, err := ps.Insert(ctx, "Quote__c", models.SObject{
		constants.FieldName: "Quote A",
		"SourceQuoteId__c":  "source-quote-001",
	}, recordEntrypointUser())
	if err != nil {
		t.Fatalf("Insert: %v", err)
	}
	assertBulkPessimisticOnly(t, txm)
}

func TestInsertNonRollupParentWithHydratedChildCloneRulesUsesPessimisticTransaction(t *testing.T) {
	repo := &nestedRollupBoundaryRepo{
		children: map[string][]models.SObject{
			"TemplateQuote__c|BundleId__c|source-bundle-001": {
				{constants.FieldID: "tmpl-quote-1", constants.FieldName: "Template Quote"},
			},
			"TemplateTask__c|QuoteId__c|source-quote-001": {
				{constants.FieldID: "tmpl-task-1", constants.FieldName: "Template Task"},
			},
		},
		existsAnyByTable: map[string]bool{"Quote__c": true, "Bundle__c": true},
		oldByTable: map[string]models.SObject{
			"Bundle__c":        {constants.FieldID: "bundle-parent"},
			"Quote__c":         {constants.FieldID: "quote-parent"},
			"TemplateQuote__c": {constants.FieldID: "tmpl-quote-1", constants.FieldName: "Template Quote", "ParentQuoteId__c": "source-quote-001"},
		},
	}
	quoteSchema := childCloneParentSchemaForBoundaryTest()
	quoteSchema.Fields = append(quoteSchema.Fields, models.FieldMetadata{
		APIName:     "BundleId__c",
		Type:        constants.FieldTypeReference,
		ReferenceTo: []string{"Bundle__c"},
		Createable:  true,
		Updateable:  true,
	})
	makeFieldsMap(quoteSchema)
	ps := newRollupBoundaryTestService(
		repo,
		parentWithRollupSchemaForBulk(),
		rollupChildSchemaWithAdditionalParentsForBoundaryTest(),
		hydratedChildCloneRootSchemaForBoundaryTest(),
		templateQuoteSchemaForBoundaryTest(),
		quoteSchema,
		templateTaskSchemaForBoundaryTest(),
	)
	txm := &recordingBulkTxManager{}
	ps.txManager = txm
	ctx := constants.WithSecurityContext(context.Background(), constants.SystemContext, "hydrated child clone root insert")

	_, err := ps.Insert(ctx, "Bundle__c", models.SObject{
		constants.FieldName: "Bundle A",
		"SourceBundleId__c": "source-bundle-001",
	}, recordEntrypointUser())
	if err != nil {
		t.Fatalf("Insert: %v", err)
	}
	assertBulkPessimisticOnly(t, txm)
}

func TestDeleteNonRollupParentWithCascadeRollupChildUsesPessimisticTransaction(t *testing.T) {
	repo := &nestedRollupBoundaryRepo{
		oldByTable: map[string]models.SObject{
			"Quote__c": {
				constants.FieldID:        "quote-001",
				constants.FieldName:      "Quote A",
				constants.FieldIsDeleted: 0,
			},
			"Task__c": {
				constants.FieldID:        "task-001",
				constants.FieldName:      "Task A",
				constants.FieldIsDeleted: 0,
			},
		},
		children: map[string][]models.SObject{
			"Task__c|QuoteId__c|quote-001": {
				{constants.FieldID: "task-001"},
			},
		},
	}
	ps := newRollupBoundaryTestService(
		repo,
		parentWithRollupSchemaForBulk(),
		rollupChildSchemaWithAdditionalParentsForBoundaryTest(),
		childCloneParentSchemaForBoundaryTest(),
	)
	txm := &recordingBulkTxManager{}
	ps.txManager = txm

	err := ps.Delete(context.Background(), "Quote__c", "quote-001", recordEntrypointUser())
	if err != nil {
		t.Fatalf("Delete: %v", err)
	}
	assertBulkPessimisticOnly(t, txm)
}

func TestDeleteNonRollupParentWithCascadeRollupChildUsesPessimisticTransactionWithoutCurrentChildren(t *testing.T) {
	repo := &nestedRollupBoundaryRepo{
		oldByTable: map[string]models.SObject{
			"Quote__c": {
				constants.FieldID:        "quote-001",
				constants.FieldName:      "Quote A",
				constants.FieldIsDeleted: 0,
			},
		},
	}
	ps := newRollupBoundaryTestService(
		repo,
		parentWithRollupSchemaForBulk(),
		rollupChildSchemaWithAdditionalParentsForBoundaryTest(),
		childCloneParentSchemaForBoundaryTest(),
	)
	txm := &recordingBulkTxManager{}
	ps.txManager = txm

	err := ps.Delete(context.Background(), "Quote__c", "quote-001", recordEntrypointUser())
	if err != nil {
		t.Fatalf("Delete: %v", err)
	}
	assertBulkPessimisticOnly(t, txm)
}

func TestDeleteNonRollupParentUsesPessimisticTransaction(t *testing.T) {
	repo := &nestedRollupBoundaryRepo{
		oldByTable: map[string]models.SObject{
			"Quote__c": {
				constants.FieldID:        "quote-001",
				constants.FieldName:      "Quote A",
				constants.FieldIsDeleted: 0,
			},
		},
	}
	quoteSchema := &models.ObjectMetadata{
		APIName:      "Quote__c",
		KeyPrefix:    runtimeStringPtr("0Q0"),
		SharingModel: constants.SharingModelPublicReadWrite,
		Fields: []models.FieldMetadata{
			{APIName: constants.FieldID, Type: constants.FieldTypeString, Createable: false, Updateable: false},
			{APIName: constants.FieldName, Type: constants.FieldTypeString, Createable: true, Updateable: true},
			{APIName: constants.FieldIsDeleted, Type: constants.FieldTypeBoolean, Createable: false, Updateable: false},
		},
	}
	ps := newRollupBoundaryTestService(
		repo,
		parentWithRollupSchemaForBulk(),
		rollupChildSchemaWithAdditionalParentsForBoundaryTest(),
		quoteSchema,
	)
	txm := &recordingBulkTxManager{}
	ps.txManager = txm

	err := ps.Delete(context.Background(), "Quote__c", "quote-001", recordEntrypointUser())
	if err != nil {
		t.Fatalf("Delete: %v", err)
	}
	assertBulkPessimisticOnly(t, txm)
}

func TestInsertParentWithDefaultedChildCloneLookupUsesPessimisticTransaction(t *testing.T) {
	repo := &nestedRollupBoundaryRepo{
		children: map[string][]models.SObject{
			"TemplateTask__c|QuoteId__c|source-quote-001": {
				{constants.FieldID: "tmpl-1", constants.FieldName: "Template task"},
			},
		},
		existsAnyByTable: map[string]bool{"Quote__c": true},
		oldByTable: map[string]models.SObject{
			"Quote__c": {constants.FieldID: "quote-parent"},
		},
	}
	ps := newRollupBoundaryTestService(
		repo,
		parentWithRollupSchemaForBulk(),
		rollupChildSchemaWithAdditionalParentsForBoundaryTest(),
		childCloneParentSchemaWithDefaultedSourceLookupForBoundaryTest(),
		templateTaskSchemaForBoundaryTest(),
	)
	txm := &recordingBulkTxManager{}
	ps.txManager = txm
	ctx := constants.WithSecurityContext(context.Background(), constants.SystemContext, "defaulted child clone lookup")

	_, err := ps.Insert(ctx, "Quote__c", models.SObject{
		constants.FieldName: "Quote A",
	}, recordEntrypointUser())
	if err != nil {
		t.Fatalf("Insert: %v", err)
	}
	assertBulkPessimisticOnly(t, txm)
}

func TestInsertParentWithAutonumberChildCloneLookupUsesPessimisticTransaction(t *testing.T) {
	repo := &nestedRollupBoundaryRepo{
		children: map[string][]models.SObject{
			"TemplateTask__c|QuoteNumber__c|AUTO-00001": {
				{constants.FieldID: "tmpl-1", constants.FieldName: "Template task"},
			},
		},
		existsAnyByTable: map[string]bool{"Quote__c": true},
		oldByTable: map[string]models.SObject{
			"Quote__c": {constants.FieldID: "quote-parent"},
		},
	}
	quoteSchema := childCloneParentSchemaForBoundaryTest()
	quoteSchema.Fields = append(quoteSchema.Fields, models.FieldMetadata{
		APIName:    "QuoteNumber",
		Type:       constants.FieldTypeString,
		Createable: true,
		Updateable: true,
	})
	quoteSchema.ChildCloneRules[0].ParentLookupField = "QuoteNumber"
	quoteSchema.ChildCloneRules[0].SourceLookupField = "QuoteNumber__c"
	makeFieldsMap(quoteSchema)

	templateSchema := templateTaskSchemaForBoundaryTest()
	templateSchema.Fields = append(templateSchema.Fields, models.FieldMetadata{
		APIName:    "QuoteNumber__c",
		Type:       constants.FieldTypeString,
		Createable: true,
		Updateable: true,
	})
	makeFieldsMap(templateSchema)

	ps := newRollupBoundaryTestService(
		repo,
		parentWithRollupSchemaForBulk(),
		rollupChildSchemaWithAdditionalParentsForBoundaryTest(),
		quoteSchema,
		templateSchema,
	)
	ps.autoNumber = &stubAutoNumberEngine{
		byFieldID: map[string][]string{"fld-quote-number": {"AUTO-00001"}},
	}
	ps.autoNumberMeta = &stubAutoNumberMeta{
		byObject: map[string][]autonumber.FieldMeta{
			"quote__c": {{FieldID: "fld-quote-number", FieldAPIName: "QuoteNumber"}},
		},
	}
	txm := &recordingBulkTxManager{}
	ps.txManager = txm
	ctx := constants.WithSecurityContext(context.Background(), constants.SystemContext, "autonumber child clone risk")

	_, err := ps.Insert(ctx, "Quote__c", models.SObject{
		constants.FieldName: "Quote A",
	}, recordEntrypointUser())
	if err != nil {
		t.Fatalf("Insert: %v", err)
	}
	assertBulkPessimisticOnly(t, txm)
}

func TestInsertParentWithCompoundChildCloneLookupUsesPessimisticTransaction(t *testing.T) {
	previous := fieldprovenance.Default()
	defer fieldprovenance.SetDefault(previous)

	payload := []byte(`[
  {
    "apiName": "Quote__c",
    "fields": [
      {"apiName": "QuoteNumber", "compoundFieldName": "Name"}
    ]
  }
]`)
	initRecordsFieldProvenanceFixture(t, payload)

	repo := &nestedRollupBoundaryRepo{
		children: map[string][]models.SObject{
			"TemplateTask__c|QuoteName__c|AUTO-00002": {
				{constants.FieldID: "tmpl-1", constants.FieldName: "Template task"},
			},
		},
		existsAnyByTable: map[string]bool{"Quote__c": true},
		oldByTable: map[string]models.SObject{
			"Quote__c": {constants.FieldID: "quote-parent"},
		},
	}
	quoteSchema := childCloneParentSchemaForBoundaryTest()
	quoteSchema.Fields = append(quoteSchema.Fields, models.FieldMetadata{
		APIName:    "QuoteNumber",
		Type:       constants.FieldTypeString,
		Createable: true,
		Updateable: true,
	})
	quoteSchema.ChildCloneRules[0].ParentLookupField = constants.FieldName
	quoteSchema.ChildCloneRules[0].SourceLookupField = "QuoteName__c"
	makeFieldsMap(quoteSchema)

	templateSchema := templateTaskSchemaForBoundaryTest()
	templateSchema.Fields = append(templateSchema.Fields, models.FieldMetadata{
		APIName:    "QuoteName__c",
		Type:       constants.FieldTypeString,
		Createable: true,
		Updateable: true,
	})
	makeFieldsMap(templateSchema)

	ps := newRollupBoundaryTestService(
		repo,
		parentWithRollupSchemaForBulk(),
		rollupChildSchemaWithAdditionalParentsForBoundaryTest(),
		quoteSchema,
		templateSchema,
	)
	ps.autoNumber = &stubAutoNumberEngine{
		byFieldID: map[string][]string{"fld-quote-number": {"AUTO-00002"}},
	}
	ps.autoNumberMeta = &stubAutoNumberMeta{
		byObject: map[string][]autonumber.FieldMeta{
			"quote__c": {{FieldID: "fld-quote-number", FieldAPIName: "QuoteNumber"}},
		},
	}
	txm := &recordingBulkTxManager{}
	ps.txManager = txm
	ctx := constants.WithSecurityContext(context.Background(), constants.SystemContext, "compound child clone risk")

	_, err := ps.Insert(ctx, "Quote__c", models.SObject{
		constants.FieldName: "Quote A",
	}, recordEntrypointUser())
	if err != nil {
		t.Fatalf("Insert: %v", err)
	}
	assertBulkPessimisticOnly(t, txm)
}

func TestDeleteNonRollupParentWithCascadeDescendantUsesPessimisticTransaction(t *testing.T) {
	repo := &nestedRollupBoundaryRepo{
		oldByTable: map[string]models.SObject{
			"Program__c": {constants.FieldID: "program-001", constants.FieldName: "Program", constants.FieldIsDeleted: 0},
			"Quote__c":   {constants.FieldID: "quote-001", constants.FieldName: "Quote", constants.FieldIsDeleted: 0},
		},
		children: map[string][]models.SObject{
			"Quote__c|ProgramId__c|program-001": {
				{constants.FieldID: "quote-001"},
			},
		},
	}
	quoteSchema := childCloneParentSchemaForBoundaryTest()
	quoteSchema.Fields = append(quoteSchema.Fields, models.FieldMetadata{
		APIName:     "ProgramId__c",
		Type:        constants.FieldTypeReference,
		ReferenceTo: []string{"Program__c"},
		Createable:  true,
		Updateable:  true,
		DeleteRule:  deleteRulePtr(constants.DeleteRuleCascade),
	})
	makeFieldsMap(quoteSchema)

	ps := newRollupBoundaryTestService(
		repo,
		parentWithRollupSchemaForBulk(),
		rollupChildSchemaWithAdditionalParentsForBoundaryTest(),
		cascadeRootSchemaForBoundaryTest(),
		quoteSchema,
	)
	txm := &recordingBulkTxManager{}
	ps.txManager = txm

	err := ps.Delete(context.Background(), "Program__c", "program-001", recordEntrypointUser())
	if err != nil {
		t.Fatalf("Delete: %v", err)
	}
	assertBulkPessimisticOnly(t, txm)
}

func TestDeleteNonRollupParentWithCascadeDescendantSchemaUsesPessimisticTransactionWithoutCurrentChildren(t *testing.T) {
	repo := &nestedRollupBoundaryRepo{
		oldByTable: map[string]models.SObject{
			"Program__c": {constants.FieldID: "program-001", constants.FieldName: "Program", constants.FieldIsDeleted: 0},
		},
	}
	quoteSchema := childCloneParentSchemaForBoundaryTest()
	quoteSchema.Fields = append(quoteSchema.Fields, models.FieldMetadata{
		APIName:     "ProgramId__c",
		Type:        constants.FieldTypeReference,
		ReferenceTo: []string{"Program__c"},
		Createable:  true,
		Updateable:  true,
		DeleteRule:  deleteRulePtr(constants.DeleteRuleCascade),
	})
	makeFieldsMap(quoteSchema)

	ps := newRollupBoundaryTestService(
		repo,
		parentWithRollupSchemaForBulk(),
		rollupChildSchemaWithAdditionalParentsForBoundaryTest(),
		cascadeRootSchemaForBoundaryTest(),
		quoteSchema,
	)
	txm := &recordingBulkTxManager{}
	ps.txManager = txm

	err := ps.Delete(context.Background(), "Program__c", "program-001", recordEntrypointUser())
	if err != nil {
		t.Fatalf("Delete: %v", err)
	}
	assertBulkPessimisticOnly(t, txm)
}

func TestInsertSiblingDefaultChildRowsRevisitSameObjectStillUsesPessimisticTransaction(t *testing.T) {
	repo := &nestedRollupBoundaryRepo{
		children: map[string][]models.SObject{
			"TemplateTask__c|QuoteId__c|source-quote-001": {
				{constants.FieldID: "tmpl-1", constants.FieldName: "Template task"},
			},
		},
		existsAnyByTable: map[string]bool{"Quote__c": true, "Bundle__c": true},
		oldByTable: map[string]models.SObject{
			"Quote__c":  {constants.FieldID: "quote-parent"},
			"Bundle__c": {constants.FieldID: "bundle-parent"},
		},
	}
	quoteSchema := childCloneParentSchemaForBoundaryTest()
	quoteSchema.Fields = append(quoteSchema.Fields, models.FieldMetadata{
		APIName:     "BundleId__c",
		Type:        constants.FieldTypeReference,
		ReferenceTo: []string{"Bundle__c"},
		Createable:  true,
		Updateable:  true,
	})
	makeFieldsMap(quoteSchema)

	ps := newRollupBoundaryTestService(
		repo,
		parentWithRollupSchemaForBulk(),
		rollupChildSchemaWithAdditionalParentsForBoundaryTest(),
		templateTaskSchemaForBoundaryTest(),
		quoteSchema,
		siblingDefaultChildRowsRootSchemaForBoundaryTest(),
	)
	txm := &recordingBulkTxManager{}
	ps.txManager = txm
	ctx := constants.WithSecurityContext(context.Background(), constants.SystemContext, "sibling default child rows")

	_, err := ps.Insert(ctx, "Bundle__c", models.SObject{
		constants.FieldName: "Bundle A",
	}, recordEntrypointUser())
	if err != nil {
		t.Fatalf("Insert: %v", err)
	}
	assertBulkPessimisticOnly(t, txm)
}
