package metadata

import (
	"context"
	"testing"

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

func userSchemaForCompoundVirtualDecoratorTest() *models.ObjectMetadata {
	return &models.ObjectMetadata{
		APIName: constants.TableUser,
		Fields: []models.FieldMetadata{
			{APIName: constants.FieldFirstName, Type: constants.FieldTypeString},
			{APIName: constants.FieldLastName, Type: constants.FieldTypeString},
		},
	}
}

func TestCompoundVirtualFieldDecorator_DoesNotInferUserNameWithoutDeclaration(t *testing.T) {
	d := NewCompoundVirtualFieldDecorator()
	input := userSchemaForCompoundVirtualDecoratorTest()
	decorated, err := d.DecorateSchema(context.Background(), input)
	if err != nil {
		t.Fatalf("DecorateSchema err = %v", err)
	}
	if decorated != input {
		t.Fatal("decorator cloned User schema without any compound virtual declaration")
	}
	if f := models.FindField(decorated, constants.FieldName); f != nil {
		t.Fatalf("Name field was synthesized without registered declaration: %+v", *f)
	}
}

func TestCompoundVirtualFieldDecorator_UsesPlatformDeclarationForUserName(t *testing.T) {
	d := NewCompoundVirtualFieldDecorator(PlatformCompoundVirtualFieldDeclarations()...)
	decorated, err := d.DecorateSchema(context.Background(), userSchemaForCompoundVirtualDecoratorTest())
	if err != nil {
		t.Fatalf("DecorateSchema err = %v", err)
	}
	name := models.FindField(decorated, constants.FieldName)
	if name == nil {
		t.Fatal("Name field missing from decorated schema")
	}
	if !name.IsVirtual || name.VirtualKind != constants.VirtualFieldCompound {
		t.Fatalf("Name virtual shape = (%v, %q), want compound virtual", name.IsVirtual, name.VirtualKind)
	}
	if !name.IsCompound || len(name.ComposedFrom) != 2 ||
		name.ComposedFrom[0] != constants.FieldFirstName ||
		name.ComposedFrom[1] != constants.FieldLastName {
		t.Fatalf("Name compound members = %+v, want [FirstName LastName]", name.ComposedFrom)
	}
}
