package audit

import (
	"strings"
	"testing"

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

func TestBuildHistoryWhereUsesStampedEligibilityWithBoundedLegacyFallback(t *testing.T) {
	where, _ := buildHistoryWhere(HistoryQueryPlan{ObjectApiName: "Account", AllowedFields: []string{"Name"}}, "001-record", "", "")
	joined := strings.Join(where, " AND ")
	for _, want := range []string{
		"FieldHistoryEligible = TRUE",
		"FieldHistoryEligible IS NULL",
		"HistorySequence IS NOT NULL",
		"_System_FieldHistoryTrackingInterval",
		"_System_AuditLog.HistorySequence > history_interval.StartedSequence",
		"_System_AuditLog.HistorySequence < history_interval.EndedSequence",
		"history_field.IsDeleted = 0",
		"history_object.IsDeleted = 0",
	} {
		if !strings.Contains(joined, want) {
			t.Fatalf("history predicate missing %q:\n%s", want, joined)
		}
	}
	if strings.Contains(joined, "HistorySequence >=") || strings.Contains(joined, "HistorySequence <=") {
		t.Fatalf("history predicate admits a boundary equality:\n%s", joined)
	}
}

func TestStampedFalseCannotFallBackToLegacyInterval(t *testing.T) {
	where, _ := buildHistoryWhere(HistoryQueryPlan{ObjectApiName: "Account", AllowedFields: []string{"Name"}}, "001-record", "", "")
	joined := strings.Join(where, " AND ")
	nullGate := strings.Index(joined, "FieldHistoryEligible IS NULL")
	sequenceGate := strings.Index(joined, "HistorySequence IS NOT NULL")
	if nullGate < 0 || sequenceGate < 0 || nullGate > sequenceGate {
		t.Fatalf("legacy fallback is not gated by NULL eligibility:\n%s", joined)
	}
	for _, forbidden := range []string{"FieldHistoryEligible = FALSE", "COALESCE(FieldHistoryEligible", "HistorySequence IS NULL", "history_interval.StartedSequence IS NULL"} {
		if strings.Contains(joined, forbidden) {
			t.Fatalf("history predicate introduced widening branch %q:\n%s", forbidden, joined)
		}
	}
}

func TestAllowedHistoryFieldNamesDefersCurrentTrackingStateToIntervals(t *testing.T) {
	schema := historySchema("Account", "Name", false)
	allowed, err := AllowedHistoryFieldNames(schema, allowAllHistoryFields{})
	if err != nil {
		t.Fatalf("AllowedHistoryFieldNames() error = %v", err)
	}
	if !containsHistoryField(allowed, "Name") {
		t.Fatalf("AllowedHistoryFieldNames() = %v, want disabled live field retained for closed-interval query", allowed)
	}
}

type allowAllHistoryFields struct{}

func (allowAllHistoryFields) HasFieldRead(string, string) (bool, error) { return true, nil }

func historySchema(objectName, fieldName string, tracked bool) *models.ObjectMetadata {
	return &models.ObjectMetadata{
		APIName: objectName,
		Fields:  []models.FieldMetadata{{APIName: fieldName, TrackHistory: tracked}},
	}
}

func containsHistoryField(fields []string, target string) bool {
	for _, field := range fields {
		if field == target {
			return true
		}
	}
	return false
}
