package bootstrapimpl

import "testing"

func TestEmailTemplateSourceBackedOwnershipSchema(t *testing.T) {
	const tableName = "_System_EmailTemplate"
	defs := GetManagedTableDefinitions()

	var found bool
	for _, def := range defs {
		if def.TableName != tableName {
			continue
		}
		found = true

		var ownerPackFound bool
		for _, col := range def.Columns {
			switch col.Name {
			case "Name":
				if col.Unique {
					t.Fatalf("%s.Name is globally unique; source-backed email_template must be scoped by OwnerPack/DeveloperName", tableName)
				}
			case "OwnerPack":
				ownerPackFound = true
				if !col.Nullable {
					t.Fatalf("%s.OwnerPack nullable = false, want nullable for historical/admin template inventory", tableName)
				}
			}
		}
		if !ownerPackFound {
			t.Fatalf("%s missing OwnerPack column", tableName)
		}

		for _, idx := range def.Indices {
			if idx.Name == "ux_email_template_owner_developer_name" &&
				idx.Unique &&
				len(idx.Columns) == 2 &&
				idx.Columns[0] == "OwnerPack" &&
				idx.Columns[1] == "DeveloperName" {
				return
			}
		}
		t.Fatalf("%s missing unique index ux_email_template_owner_developer_name on (OwnerPack, DeveloperName); declared indices: %v", tableName, def.Indices)
	}

	if !found {
		t.Fatalf("%s not found in system_tables.json", tableName)
	}
}
