package schema

import (
	"sort"
	"testing"

	"github.com/nexuscrm/shared/pkg/models"
)

func TestRelationshipFKColumns(t *testing.T) {
	defs := []TableDefinition{
		{
			TableName: "OrderLike",
			Columns: []ColumnDefinition{
				// Injected system columns: reference-typed in metadata but carry no
				// ReferenceTo on the column def, and IsSystemField-guarded.
				{Name: "Id", Type: "VARCHAR(255)", PrimaryKey: true},
				{Name: "OwnerId", Type: "VARCHAR(255)"},
				{Name: "RecordTypeId", Type: "VARCHAR(255)"},
				// Business relationship FK columns — must be selected.
				{Name: "AccountId", Type: "VARCHAR(255)", ReferenceTo: []string{"Account"}},
				{Name: "ContractId", Type: "VARCHAR(255)", ReferenceTo: []string{"Contract"}, IsMasterDetail: true},
				{Name: "WhatId", Type: "VARCHAR(255)", ReferenceTo: []string{"Account", "Opportunity"}, IsPolymorphic: true},
				// Polymorphic discriminator + a plain field — must not be selected.
				{Name: "WhatId_type", Type: "VARCHAR(255)", GeneratedForPolymorphicReference: "WhatId"},
				{Name: "Description", Type: "TEXT"},
			},
		},
		{
			// Metadata-only object: owns no physical table here, must be skipped
			// even though it has a relationship column.
			TableName:  "LegacyView",
			ReadSource: &models.ObjectReadSourceConfig{PhysicalTable: "legacy_view_src"},
			Columns: []ColumnDefinition{
				{Name: "ParentId", Type: "VARCHAR(255)", ReferenceTo: []string{"Account"}},
			},
		},
	}

	got := make([]string, 0)
	for _, fk := range RelationshipFKColumns(defs) {
		if fk.Table != "OrderLike" {
			t.Errorf("unexpected table %q selected (ReadSource def should be skipped)", fk.Table)
		}
		got = append(got, fk.Column)
	}
	sort.Strings(got)

	want := []string{"AccountId", "ContractId", "WhatId"}
	if len(got) != len(want) {
		t.Fatalf("RelationshipFKColumns = %v, want %v", got, want)
	}
	for i := range want {
		if got[i] != want[i] {
			t.Fatalf("RelationshipFKColumns = %v, want %v", got, want)
		}
	}
}
