package bootstrapimpl

import (
	"testing"
)

// TestSystemTableScheduledRunReservationDefinitionPinned locks in the additive
// L0 infrastructure table for issue #647. The scheduler reservation substrate
// is internal automation state, not an app-shaped metadata surface and not a
// generic CRUD object. The declaration therefore must stay in system_tables.json
// with both read/write gates blocked and one unique index over the canonical
// occurrence digest. The digest preserves the stopped-upgrade identity while
// allowing the durable worker schema to carry lease and ownership fencing.
func TestSystemTableScheduledRunReservationDefinitionPinned(t *testing.T) {
	defs := GetManagedTableDefinitions()
	for _, def := range defs {
		if def.TableName != "_System_ScheduledRunReservation" {
			continue
		}
		if def.TableType != "system_core" {
			t.Fatalf("_System_ScheduledRunReservation.TableType = %q, want %q", def.TableType, "system_core")
		}
		if def.Category != "automation" {
			t.Fatalf("_System_ScheduledRunReservation.Category = %q, want %q", def.Category, "automation")
		}
		if def.RequiredReadPermission != "BLOCKED" {
			t.Fatalf("_System_ScheduledRunReservation.requiredReadPermission = %q, want %q", def.RequiredReadPermission, "BLOCKED")
		}
		if def.RequiredWritePermission != "BLOCKED" {
			t.Fatalf("_System_ScheduledRunReservation.requiredWritePermission = %q, want %q", def.RequiredWritePermission, "BLOCKED")
		}

		wantCols := map[string]struct{}{
			"Id":                       {},
			"OrgId":                    {},
			"AppInstallationId":        {},
			"RuntimeCapabilityId":      {},
			"OccurrenceIdentityDigest": {},
			"FlowDefinitionId":         {},
			"FlowVersionId":            {},
			"ScheduleWindowKey":        {},
			"WindowToken":              {},
			"InputKey":                 {},
			"State":                    {},
			"Status":                   {},
			"Attempt":                  {},
			"LeaseToken":               {},
			"LeaseExpiresAt":           {},
			"OwnershipEpoch":           {},
			"ReservedAt":               {},
			"CompletedAt":              {},
			"LastError":                {},
			"CreatedDate":              {},
			"LastModifiedDate":         {},
		}
		for _, col := range def.Columns {
			delete(wantCols, col.Name)
		}
		if len(wantCols) != 0 {
			t.Fatalf("_System_ScheduledRunReservation missing expected columns: %#v", wantCols)
		}

		for _, idx := range def.Indices {
			if !idx.Unique {
				continue
			}
			if len(idx.Columns) != 1 {
				continue
			}
			if idx.Columns[0] == "OccurrenceIdentityDigest" {
				return
			}
		}
		t.Fatal("_System_ScheduledRunReservation unique index on OccurrenceIdentityDigest missing")
	}

	t.Fatal("_System_ScheduledRunReservation entry missing from system_tables.json")
}
