package persistence

import (
	"context"
	"errors"
	"testing"

	"github.com/nexuscrm/persistence/layoutroutingsecurity"
)

func TestLayoutRoutingSecurityStrictV2ShadowRenamesIntoTheCanonicalPairOnTiDB(t *testing.T) {
	db, cleanup := openSessionRepositoryTiDB(t)
	defer cleanup()
	ctx := context.Background()

	if _, err := db.ExecContext(ctx, `CREATE TABLE _System_RuntimeSecurityState (
OrgId VARCHAR(255) PRIMARY KEY,
RuntimeAudience VARCHAR(255) NOT NULL,
SecurityEpoch DECIMAL(20,0) NOT NULL,
CreatedDate DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
LastModifiedDate DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6))`); err != nil {
		t.Fatal(err)
	}
	if tables, err := layoutroutingsecurity.VerifyLive(ctx, db); !errors.Is(err, layoutroutingsecurity.ErrSchema) || tables != nil {
		t.Fatalf("legacy live pair = (%#v, %v), want (nil, ErrSchema)", tables, err)
	}
	for attempt := 1; attempt <= 2; attempt++ {
		if _, err := layoutroutingsecurity.CreateHaltedShadow(ctx, db); err != nil {
			t.Fatalf("CreateHaltedShadow attempt %d: %v", attempt, err)
		}
	}

	if _, err := db.ExecContext(ctx, `RENAME TABLE
_System_RuntimeSecurityState TO _System_RuntimeSecurityStateV1Archive,
_System_RuntimeSecurityStateV2Shadow TO _System_RuntimeSecurityState,
_System_LayoutRoutingSecurityAttestationV2Shadow TO _System_LayoutRoutingSecurityAttestation`); err != nil {
		t.Fatal(err)
	}
	if _, err := layoutroutingsecurity.VerifyLive(ctx, db); err != nil {
		t.Fatalf("VerifyLive after halted rename: %v", err)
	}
}
