package records

import (
	"testing"

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

func TestApplyCompoundNameSynthesisUsesSourceBackedChildCompoundDeclarations(t *testing.T) {
	previous := fieldprovenance.Default()
	defer fieldprovenance.SetDefault(previous)

	payload := []byte(`[
  {
    "apiName": "Contact",
    "fields": [
      {"apiName": "Salutation", "compoundFieldName": "Name"},
      {"apiName": "FirstName", "compoundFieldName": "Name"},
      {"apiName": "LastName", "isNameField": true, "compoundFieldName": "Name"}
    ]
  }
]`)
	initRecordsFieldProvenanceFixture(t, payload)

	schema := &models.ObjectMetadata{
		APIName: "Contact",
		Fields: []models.FieldMetadata{
			{APIName: constants.FieldName},
			{APIName: "Salutation"},
			{APIName: "FirstName"},
			{APIName: "LastName", IsNameField: true},
		},
	}
	data := map[string]interface{}{
		"Salutation": "Dr.",
		"FirstName":  "Ada",
		"LastName":   "Lovelace",
	}

	applyCompoundNameSynthesis(schema, data, false)

	if got, want := data[constants.FieldName], "Dr. Ada Lovelace"; got != want {
		t.Fatalf("synthesized Contact.Name = %#v, want %q", got, want)
	}
}

func TestResolveRequestBoundCompoundFieldsUsesImmutableSchema(t *testing.T) {
	previous := fieldprovenance.Default()
	t.Cleanup(func() { fieldprovenance.SetDefault(previous) })
	fieldprovenance.SetDefault(nil)

	schema := &models.ObjectMetadata{
		APIName: "Quote",
		Fields: []models.FieldMetadata{
			{APIName: constants.FieldName, IsCompound: true, ComposedFrom: []string{"QuoteNumber"}},
			{APIName: "QuoteNumber"},
		},
	}
	data := models.SObject{"QuoteNumber": "QT-0001"}

	resolveRequestBoundCompoundFields(schema, data)

	if got := data[constants.FieldName]; got != "QT-0001" {
		t.Fatalf("request-bound Quote.Name = %#v, want QT-0001", got)
	}
}

func TestResolveRequestBoundCompoundFieldsHasNoProcessGlobalFallback(t *testing.T) {
	previous := fieldprovenance.Default()
	t.Cleanup(func() { fieldprovenance.SetDefault(previous) })
	initRecordsFieldProvenanceFixture(t, []byte(`[
  {
    "apiName": "Quote",
    "fields": [
      {"apiName": "Name"},
      {"apiName": "QuoteNumber", "compoundFieldName": "Name"}
    ]
  }
]`))

	// The immutable request schema deliberately does not declare a compound
	// parent. Process-global installation state must not widen that revision.
	schema := &models.ObjectMetadata{
		APIName: "Quote",
		Fields: []models.FieldMetadata{
			{APIName: constants.FieldName},
			{APIName: "QuoteNumber"},
		},
	}
	data := models.SObject{"QuoteNumber": "QT-0002"}

	resolveRequestBoundCompoundFields(schema, data)

	if _, exists := data[constants.FieldName]; exists {
		t.Fatalf("request-bound metadata used process-global compound fallback: %#v", data)
	}
}
