package analytics

import (
	"testing"

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

// TestNeutralQueryResultNeutralizesNestedSubqueryRecords guards the C10 invariant:
// child-relationship subquery results are attached by executeSubQueries as a
// neutral []models.SObject slice (no SF {totalSize,done,records} envelope minted
// in app-blind L0), and neutralQueryResultFromModel must NOT let that concrete
// models.SObject type cross the contract.Query boundary — nested rows must be
// neutralized to []neutralcontract.Record (attributes stripped) at every depth,
// exactly like top-level rows. The L1 dialect re-wraps the SF envelope from these
// neutral records.
func TestNeutralQueryResultNeutralizesNestedSubqueryRecords(t *testing.T) {
	got := neutralQueryResultFromModel(&models.QueryResult{
		TotalSize: 1,
		Done:      true,
		Records: []models.SObject{{
			"Id": "001",
			"Contacts": []models.SObject{
				{"Id": "003a", "attributes": map[string]interface{}{"type": "Contact"}},
				{"Id": "003b"},
			},
		}},
	})
	if got == nil || len(got.Records) != 1 {
		t.Fatalf("neutral result = %#v", got)
	}

	nested, ok := got.Records[0]["Contacts"].([]neutralcontract.Record)
	if !ok {
		t.Fatalf("nested subquery leaked concrete type %T; want []neutralcontract.Record", got.Records[0]["Contacts"])
	}
	if len(nested) != 2 {
		t.Fatalf("nested records = %#v, want 2", nested)
	}
	if _, leaked := interface{}(nested[0]).(models.SObject); leaked {
		t.Fatalf("nested record kept models.SObject concrete type: %#v", nested[0])
	}
	if _, hasAttrs := nested[0]["attributes"]; hasAttrs {
		t.Fatalf("nested record kept SF attributes envelope: %#v", nested[0])
	}
	if nested[0]["Id"] != "003a" {
		t.Fatalf("nested record Id = %v, want 003a", nested[0]["Id"])
	}
}
