package bootstrapimpl

import (
	"testing"

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

func TestSystemListViewOwnershipColumnsPinned(t *testing.T) {
	defs := GetManagedTableDefinitions()
	for _, def := range defs {
		if def.TableName != "_System_ListView" {
			continue
		}

		columns := map[string]schema.ColumnDefinition{}
		for _, col := range def.Columns {
			columns[col.Name] = col
		}

		for _, name := range []string{"OwnerId", "Visibility", "DeveloperName"} {
			col, ok := columns[name]
			if !ok {
				t.Fatalf("_System_ListView.%s column missing", name)
			}
			if !col.Nullable {
				t.Fatalf("_System_ListView.%s nullable = false, want true for legacy-row compatibility", name)
			}
			if col.Type != "VARCHAR(255)" {
				t.Fatalf("_System_ListView.%s type = %q, want VARCHAR(255)", name, col.Type)
			}
		}

		if !hasIndexColumns(def, []string{"ObjectApiName"}) {
			t.Fatal("_System_ListView missing ObjectApiName index")
		}
		if !hasIndexColumns(def, []string{"ObjectApiName", "OwnerId"}) {
			t.Fatal("_System_ListView missing ObjectApiName,OwnerId index")
		}
		return
	}
	t.Fatal("_System_ListView entry missing from system_tables.json")
}

func hasIndexColumns(def schema.TableDefinition, want []string) bool {
	for _, idx := range def.Indices {
		if len(idx.Columns) != len(want) {
			continue
		}
		match := true
		for i := range want {
			if idx.Columns[i] != want[i] {
				match = false
				break
			}
		}
		if match {
			return true
		}
	}
	return false
}
