package analytics

import (
	"testing"

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

// TestProjectExplicitRelationshipSelectionsStampsNeutralObjectType locks the
// projectExplicitRelationshipSelections object-type stamp. The feature layer now
// produces neutral object-type metadata; v63 attributes are projected later at
// the REST dialect boundary.
//
// Input construction (mirrors query_helpers_displayname_test.go):
//   - schema "Contact" with a single concrete lookup field "AccountId"
//     (Type=reference, ReferenceTo=["Account"], RelationshipName="Account").
//     canHydrateDotNotationLookup passes (reference, non-polymorphic, exactly
//     one non-empty ReferenceTo), and relationshipNameForField returns "Account".
//   - selectFields ["Account.Name"]: lookupFieldForDotNotation resolves parent
//     "Account" via findLookupByRelationshipName -> AccountId field; child "Name".
//   - row carries "AccountId_Name" so the child==Name branch fires
//     (addedChild=true). With no pre-existing "Account" relationship object,
//     the absent-attributes branch runs and stamps ReferenceTo[0]="Account".
func TestProjectExplicitRelationshipSelectionsStampsNeutralObjectType(t *testing.T) {
	accountRel := "Account"
	schema := &models.ObjectMetadata{
		APIName: "Contact",
		Fields: []models.FieldMetadata{
			{APIName: constants.FieldID, Type: constants.FieldTypeString, IsSystem: true},
			{
				APIName:          "AccountId",
				Type:             constants.FieldTypeReference,
				ReferenceTo:      []string{"Account"},
				RelationshipName: &accountRel,
			},
		},
	}

	rows := []models.SObject{
		{
			constants.FieldID: "003000000000001",
			"AccountId":       "001000000000001",
			"AccountId_Name":  "Acme Inc",
		},
	}

	out := projectExplicitRelationshipSelections(schema, rows, []string{"Account.Name"})

	if len(out) != 1 {
		t.Fatalf("rows = %d, want 1", len(out))
	}
	nested, ok := out[0]["Account"].(map[string]interface{})
	if !ok {
		t.Fatalf("nested Account relationship missing or wrong type: %#v", out[0])
	}

	if got := models.RecordObjectType(nested); got != "Account" {
		t.Fatalf("nested object type = %q, want Account; nested=%#v", got, nested)
	}
	if _, ok := nested["attributes"]; ok {
		t.Fatalf("feature layer emitted v63 attributes before dialect projection: %#v", nested)
	}

	// Sanity: the relationship child projection actually ran (addedChild path).
	if nested[constants.FieldName] != "Acme Inc" {
		t.Fatalf("nested Name = %#v, want \"Acme Inc\"", nested[constants.FieldName])
	}
}
