package kb

import (
	"context"
	"fmt"
	"strings"
)

func (s *Store) CountSourceMirrorsByCredentialRefs(ctx context.Context, workspaceID string, credentialRefs []string) (map[string]int64, error) {
	if err := s.ensureDB(); err != nil {
		return nil, err
	}
	refs := uniqueTrimmedStrings(credentialRefs)
	if len(refs) == 0 {
		return map[string]int64{}, nil
	}
	var rows []struct {
		CredentialRef string
		Count         int64
	}
	err := s.db.WithContext(ctx).
		Model(&SourceMirror{}).
		Select("credential_ref, COUNT(*) AS count").
		Where("workspace_id = ? AND credential_ref IN ?", strings.TrimSpace(workspaceID), refs).
		Group("credential_ref").
		Find(&rows).Error
	if err != nil {
		return nil, fmt.Errorf("count source mirrors by credential refs: %w", err)
	}
	counts := make(map[string]int64, len(refs))
	for _, ref := range refs {
		counts[ref] = 0
	}
	for _, row := range rows {
		counts[strings.TrimSpace(row.CredentialRef)] = row.Count
	}
	return counts, nil
}
