package persistence

import (
	"testing"

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

// TestIntegration_ConnectorIngressFenceEpochUpgradePreservesPreexistingRow
// exercises the production add-column planner against the pre-FenceEpoch
// control-table shape. A zero value is deliberately not receipt-safe: the
// connector admission writer is the only component allowed to advance it.
func TestIntegration_ConnectorIngressFenceEpochUpgradePreservesPreexistingRow(t *testing.T) {
	db, cleanup := openSchemaDDLTiDB(t)
	defer cleanup()

	mustExec(t, db, `CREATE TABLE _System_ConnectorIngressControl (
		Id VARCHAR(255) PRIMARY KEY,
		Namespace VARCHAR(255) NOT NULL,
		PackInstallId VARCHAR(255) NOT NULL DEFAULT '',
		Channel VARCHAR(255) NOT NULL,
		Mode VARCHAR(32) NOT NULL DEFAULT 'active',
		RetryAfterSeconds INT NOT NULL DEFAULT 120,
		Reason VARCHAR(255) NULL,
		RequestedBy VARCHAR(255) NULL,
		ExpiresAt DATETIME NULL,
		IsDeleted TINYINT(1) NOT NULL DEFAULT 0,
		CreatedDate DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
		LastModifiedDate DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
		UNIQUE KEY uniq_connector_ingress_control_scope (Namespace, PackInstallId, Channel)
	)`)
	mustExec(t, db, `INSERT INTO _System_ConnectorIngressControl
		(Id, Namespace, PackInstallId, Channel, Mode, RetryAfterSeconds, IsDeleted)
		VALUES ('legacy-global', 'hubspot-crm-connector', '', '*', 'active', 120, 0)`)

	defs, err := schemacatalog.SystemTableDefinitions()
	if err != nil {
		t.Fatalf("SystemTableDefinitions: %v", err)
	}
	var statements []string
	for _, table := range defs {
		if table.TableName != "_System_ConnectorIngressControl" {
			continue
		}
		for _, column := range table.Columns {
			if column.Name == "FenceEpoch" {
				statements = PlanAddColumnStatements(table.TableName, column.Name, column.Type, column.Nullable, column.Default, column.CollationName)
			}
		}
	}
	if len(statements) == 0 {
		t.Fatal("system catalog did not provide _System_ConnectorIngressControl.FenceEpoch upgrade DDL")
	}
	for _, statement := range statements {
		mustExec(t, db, statement)
	}

	var namespace, mode string
	var epoch int64
	if err := db.QueryRow(`SELECT Namespace, Mode, FenceEpoch FROM _System_ConnectorIngressControl WHERE Id = 'legacy-global'`).Scan(&namespace, &mode, &epoch); err != nil {
		t.Fatalf("read upgraded legacy control row: %v", err)
	}
	if namespace != "hubspot-crm-connector" || mode != "active" || epoch != 0 {
		t.Fatalf("upgraded legacy row = namespace=%q mode=%q epoch=%d, want preserved active row at epoch 0", namespace, mode, epoch)
	}

	mustExec(t, db, `UPDATE _System_ConnectorIngressControl SET FenceEpoch = FenceEpoch + 1 WHERE Id = 'legacy-global'`)
	if err := db.QueryRow(`SELECT FenceEpoch FROM _System_ConnectorIngressControl WHERE Id = 'legacy-global'`).Scan(&epoch); err != nil {
		t.Fatalf("read advanced legacy control row: %v", err)
	}
	if epoch != 1 {
		t.Fatalf("upgraded legacy FenceEpoch = %d, want writable monotonic value 1", epoch)
	}
}
