package validation

import (
	"strings"
	"testing"

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

// TestValidateSchemaCompliance_RejectsRollupSummary_ByDefault locks in the
// baseline read-only behavior: a write to a RollupSummary field is rejected
// when the caller did not opt into derived recompute.
func TestValidateSchemaCompliance_RejectsRollupSummary_ByDefault(t *testing.T) {
	v := NewSchemaValidator()
	schema := &models.ObjectMetadata{
		APIName: "Account",
		Fields: []models.FieldMetadata{
			{APIName: "TotalAmount__c", Type: constants.FieldTypeRollupSummary},
		},
	}
	data := models.SObject{"TotalAmount__c": float64(42)}

	err := v.ValidateSchemaCompliance(data, schema, true /*isUpdate*/, false /*allowSystemFields*/, false /*allowDerivedRecompute*/)
	if err == nil {
		t.Fatal("expected RollupSummary write to be rejected when allowDerivedRecompute=false; got nil")
	}
	if !strings.Contains(err.Error(), "RollupSummary") {
		t.Errorf("expected RollupSummary rejection message, got: %v", err)
	}
}

// TestValidateSchemaCompliance_AllowsRollupSummary_WhenDerivedRecompute proves
// the carve-out enables the records-package UpdateDerived path. Formulas and
// AutoNumber remain rejected regardless — only RollupSummary opens up.
func TestValidateSchemaCompliance_AllowsRollupSummary_WhenDerivedRecompute(t *testing.T) {
	v := NewSchemaValidator()
	schema := &models.ObjectMetadata{
		APIName: "Account",
		Fields: []models.FieldMetadata{
			{APIName: "TotalAmount__c", Type: constants.FieldTypeRollupSummary},
		},
	}
	data := models.SObject{"TotalAmount__c": float64(42)}

	if err := v.ValidateSchemaCompliance(data, schema, true, false, true /*allowDerivedRecompute*/); err != nil {
		t.Fatalf("expected RollupSummary write to pass when allowDerivedRecompute=true; got %v", err)
	}
}

// TestValidateSchemaCompliance_AllowDerivedRecompute_DoesNotUnlockFormula
// proves the carve-out is RollupSummary-only. Formulas remain rejected even
// when the caller passes allowDerivedRecompute=true.
func TestValidateSchemaCompliance_AllowDerivedRecompute_DoesNotUnlockFormula(t *testing.T) {
	v := NewSchemaValidator()
	formula := "Amount * 2"
	schema := &models.ObjectMetadata{
		APIName: "Account",
		Fields: []models.FieldMetadata{
			{APIName: "Doubled__c", Type: constants.FieldTypeDouble, Formula: &formula},
		},
	}
	data := models.SObject{"Doubled__c": float64(42)}

	err := v.ValidateSchemaCompliance(data, schema, true, false, true)
	if err == nil {
		t.Fatal("expected Formula write to remain rejected even when allowDerivedRecompute=true")
	}
	if !strings.Contains(err.Error(), "formula") && !strings.Contains(err.Error(), "Formula") {
		t.Errorf("expected formula rejection message, got: %v", err)
	}
}
