package analytics

import (
	"context"
	"testing"

	domainSchema "github.com/nexuscrm/kernel/pkg/schema"
	"github.com/nexuscrm/shared/pkg/models"
)

type indexedRollupMetadataStub struct {
	MetadataSource
	dependencies []domainSchema.RollupChildDependency
	indexedCalls int
	fullCalls    int
}

func (s *indexedRollupMetadataStub) RollupChildDependencies(context.Context, string) []domainSchema.RollupChildDependency {
	s.indexedCalls++
	return s.dependencies
}

func (s *indexedRollupMetadataStub) HasRollupChildDependencies(context.Context, string) bool {
	s.indexedCalls++
	return len(s.dependencies) > 0
}

func (s *indexedRollupMetadataStub) GetSchemas(context.Context) []*models.ObjectMetadata {
	s.fullCalls++
	return nil
}

func TestRollupMetadataUsesNarrowIndexedAuthority(t *testing.T) {
	source := &indexedRollupMetadataStub{dependencies: []domainSchema.RollupChildDependency{{
		ParentObjectAPIName: "Account",
		RollupField: models.FieldMetadata{
			APIName:      "Total__c",
			RollupConfig: &models.RollupConfig{SummaryObject: "Opportunity"},
		},
	}}}

	dependencies := rollupChildDependencies(t.Context(), source, "Opportunity")
	if len(dependencies) != 1 || dependencies[0].ParentObjectAPIName != "Account" {
		t.Fatalf("dependencies = %#v", dependencies)
	}
	if !hasRollupChildDependencies(t.Context(), source, "Opportunity") {
		t.Fatal("indexed rollup presence was lost")
	}
	if source.indexedCalls != 2 || source.fullCalls != 0 {
		t.Fatalf("metadata calls indexed/full = %d/%d, want 2/0", source.indexedCalls, source.fullCalls)
	}
}
