package bootstrap

import (
	"encoding/json"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestStandardFieldMappings_LeadConvertScopeMatchesMetadataDrivenPRD(t *testing.T) {
	var groups []FieldMappingGroup
	require.NoError(t, json.Unmarshal(standardFieldMappingsJSON, &groups))

	byTarget := map[string]*FieldMappingGroup{}
	for _, group := range groups {
		if group.SourceObject != "Lead" || group.ActionType != "convert" {
			continue
		}
		group := group
		byTarget[group.TargetObject] = &group
		require.NotEmptyf(t, group.Mappings, "Lead -> %s convert mapping group must declare fields", group.TargetObject)
		for _, mapping := range group.Mappings {
			assert.NotContains(t, mapping.SourceField, "__c",
				"public standard Lead Convert mappings must not ship tenant custom fields")
		}
	}

	contact := byTarget["Contact"]
	require.NotNil(t, contact, "Lead -> Contact mappings are in scope for metadata-driven convert")
	assert.Len(t, contact.Mappings, 26, "Phase 1 standard-core Contact mapping count must match the design")

	account := byTarget["Account"]
	require.NotNil(t, account, "Lead -> Account mapping powers the declarative CreateAccount path when accountId is omitted")
	assert.Len(t, account.Mappings, 15, "Phase 1 standard-core Account mapping count must match the design")
	assertMappingTarget(t, account.Mappings, "Company", "Name")
	assertMappingTarget(t, account.Mappings, "OwnerId", "OwnerId")
	assertMappingTarget(t, account.Mappings, "LeadSource", "AccountSource")

	opportunity := byTarget["Opportunity"]
	require.NotNil(t, opportunity, "Lead -> Opportunity mappings are in scope for metadata-driven convert")
	assert.Len(t, opportunity.Mappings, 4, "Phase 1 standard-core Opportunity mappings include the UI-visible Name prefill plus LeadSource, Description, and OwnerId")
	assertMappingTarget(t, opportunity.Mappings, "Company", "Name")
	assertMappingTarget(t, opportunity.Mappings, "LeadSource", "LeadSource")
	assertMappingTarget(t, opportunity.Mappings, "Description", "Description")
	assertMappingTarget(t, opportunity.Mappings, "OwnerId", "OwnerId")
}

func assertMappingTarget(t *testing.T, mappings []FieldMappingDef, sourceField, targetField string) {
	t.Helper()
	for _, mapping := range mappings {
		if mapping.SourceField == sourceField {
			assert.Equal(t, targetField, mapping.TargetField)
			return
		}
	}
	t.Fatalf("missing mapping for source field %s", sourceField)
}
