import { mapComponentNameToDomain } from './domain-mapping.rules';

export interface SuspectedComponentLeak {
  name: string;
  count: number;
  expected: number;
}

export function aggregateComponentCountsByDomain(
  componentCounts: Record<string, number>
): Record<string, number> {
  const domains: Record<string, number> = {};

  for (const [componentName, count] of Object.entries(componentCounts)) {
    const domain = mapComponentNameToDomain(componentName);

    domains[domain] = (domains[domain] ?? 0) + count;
  }

  return domains;
}

export function detectSuspectedComponentLeaks(
  componentCounts: Record<string, number>,
  expectedCounts: Record<string, number>
): SuspectedComponentLeak[] {
  const leaks: SuspectedComponentLeak[] = [];

  for (const [name, count] of Object.entries(componentCounts)) {
    const expected = expectedCounts[name] ?? 0;

    if (count > expected) {
      leaks.push({ name, count, expected });
    }
  }

  return leaks.sort((left, right) => right.count - left.count);
}
