package records

import (
	"strings"
	"testing"

	"github.com/nexuscrm/kernel/pkg/schema"
	"github.com/nexuscrm/kernel/pkg/schemacatalog"
	"github.com/nexuscrm/persistence"
)

func TestRuntimeRollupCutoverRejectsLateOldWriterUntilFinalBackfillTiDB(t *testing.T) {
	db, cleanup := openRecordsHistoryTiDB(t)
	defer cleanup()
	definitions, err := schemacatalog.SystemTableDefinitions()
	if err != nil {
		t.Fatal(err)
	}
	var canonical schema.TableDefinition
	for _, def := range definitions {
		if def.TableName == "_System_RollupDelta" {
			canonical = def
			break
		}
	}
	if canonical.TableName == "" {
		t.Fatal("canonical Rollup queue absent")
	}
	repo := persistence.NewSchemaRepository(db, nil)
	if err := repo.CreatePhysicalTable(t.Context(), canonical); err != nil {
		t.Fatal(err)
	}
	if err := VerifyRuntimeRollupDeltaQueueSchema(t.Context(), db); err != nil {
		t.Fatal(err)
	}
	binding := runtimeRollupBinding()
	// This is the released producer's INSERT shape: all authoritative Runtime
	// binding fields are present, but the newly added digest is not authored.
	if _, err := db.Exec(`INSERT INTO _System_RollupDelta
(Id, SourceObject, SourceRecordId, ParentObject, ParentRecordId, RollupField, Delta, DedupeKey,
 OrgId, AppInstallationId, RuntimeCapabilityId, CatalogRevision, SchemaGeneration, EngineGeneration,
 CatalogSnapshotDigest, RuntimeMetadataViewDigest, Status)
VALUES ('late-old-writer', 'Child', 'child-1', 'Parent', 'parent-1', 'Count', 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')`,
		strings.Repeat("a", 64), binding.OrgID, binding.AppInstallationID, binding.RuntimeCapabilityID, binding.CatalogRevision,
		binding.SchemaGeneration, binding.EngineGeneration, binding.CatalogSnapshotDigest, binding.RuntimeMetadataViewDigest); err != nil {
		t.Fatal(err)
	}
	for _, status := range []string{"pending", "failed"} {
		if _, err := db.Exec(`UPDATE _System_RollupDelta SET Status=? WHERE Id='late-old-writer'`, status); err != nil {
			t.Fatal(err)
		}
		if err := VerifyRuntimeRollupDeltaQueueSchema(t.Context(), db); err == nil || !strings.Contains(err.Error(), "missing ScopeDigest") {
			t.Fatalf("%s old-writer row passed readiness: %v", status, err)
		}
	}
	// The deployment owner now has every old Runtime writer stopped/drained and
	// reapplies the canonical migration; a second pass must be idempotent.
	if _, err := db.Exec(`UPDATE _System_RollupDelta SET Status='pending' WHERE Id='late-old-writer'`); err != nil {
		t.Fatal(err)
	}
	for range 2 {
		if err := repo.CreatePhysicalTable(t.Context(), canonical); err != nil {
			t.Fatal(err)
		}
	}
	if err := VerifyRuntimeRollupDeltaQueueSchema(t.Context(), db); err != nil {
		t.Fatal(err)
	}
	scope := persistence.RuntimeWorkScope{OrgID: binding.OrgID, AppInstallationID: binding.AppInstallationID, RuntimeCapabilityID: binding.RuntimeCapabilityID}
	ps := &PersistenceService{rollupDeltaWorker: &runtimeRollupDeltaWorkerConfig{db: db, scope: scope}}
	id, loaded, found, err := ps.peekRollupDeltaBinding(t.Context(), nil)
	if err != nil || !found || id != "late-old-writer" || loaded != binding {
		t.Fatalf("backfilled old write is not visible with its original binding: id=%s found=%v binding=%+v err=%v", id, found, loaded, err)
	}
}
