package schemacatalog

import (
	"testing"

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

func TestSystemTableWriteProtectionInventoryUsesLogicalAndPhysicalFieldNames(t *testing.T) {
	inventory, err := systemTableWriteProtectionInventoryFromDefinitions([]schema.TableDefinition{{
		TableName: "NeutralControl",
		Columns: []schema.ColumnDefinition{
			{
				Name:                  "AuthorityValue",
				PhysicalName:          "authority_value",
				WriteProtectionPolicy: constants.FieldWriteProtectionAuthorityOnly,
			},
		},
	}})
	if err != nil {
		t.Fatalf("systemTableWriteProtectionInventoryFromDefinitions(): %v", err)
	}

	for _, fieldName := range []string{"AuthorityValue", "authorityvalue", "authority_value", "AUTHORITY_VALUE"} {
		fact, ok := inventory.lookup("neutralcontrol", fieldName)
		if !ok {
			t.Fatalf("lookup(%q) = not found", fieldName)
		}
		if fact.FieldName != "AuthorityValue" ||
			fact.PhysicalName != "authority_value" ||
			fact.Policy != constants.FieldWriteProtectionAuthorityOnly {
			t.Fatalf("lookup(%q) = %+v, want AuthorityValue/authority_value/authority_only", fieldName, fact)
		}
	}

}

func TestFieldPolicyDeclarationIsInCanonicalWriteProtectionInventory(t *testing.T) {
	fact, ok, err := SystemTableFieldWriteProtectionFor("_system_field", "WriteProtectionPolicy")
	if err != nil {
		t.Fatalf("SystemTableFieldWriteProtectionFor(): %v", err)
	}
	if !ok {
		t.Fatal("SystemTableFieldWriteProtectionFor() = not found")
	}
	if fact.FieldName != "WriteProtectionPolicy" ||
		fact.PhysicalName != "WriteProtectionPolicy" ||
		fact.Policy != constants.FieldWriteProtectionAuthorityOnly {
		t.Fatalf("SystemTableFieldWriteProtectionFor() = %+v, want authority_only", fact)
	}
}
