import { describe, expect, test } from 'vitest';
import { datasetUsageCounts, snippetsReferencingDataset } from './relationships';

/** A minimal snippet-like record — the helpers only read `datasetRefs`. */
const snip = (id: string, datasetRefs: string[]) => ({ id, datasetRefs });

describe('snippetsReferencingDataset', () => {
  const snippets = [
    snip('a', ['Sales']),
    snip('b', ['SALES', 'Regions']),
    snip('c', ['Other']),
    snip('d', []),
  ];

  test('matches case-insensitively and preserves the input records', () => {
    expect(snippetsReferencingDataset(snippets, 'sales').map((s) => s.id)).toEqual(['a', 'b']);
    // The matched element is the same object that was passed in (no remapping).
    expect(snippetsReferencingDataset(snippets, 'sales')[0]).toBe(snippets[0]);
  });

  test('returns an empty array when nothing references the name', () => {
    expect(snippetsReferencingDataset(snippets, 'Nonexistent')).toEqual([]);
  });
});

describe('datasetUsageCounts', () => {
  test('counts every reference, keyed by lower-cased name, in one pass', () => {
    const counts = datasetUsageCounts([
      snip('a', ['Sales']),
      snip('b', ['SALES', 'Regions']),
      snip('c', ['regions']),
    ]);
    expect(counts.get('sales')).toBe(2);
    expect(counts.get('regions')).toBe(2);
    expect(counts.get('other')).toBeUndefined();
  });

  test('is empty for a library with no references', () => {
    expect(datasetUsageCounts([snip('a', []), snip('b', [])]).size).toBe(0);
  });
});
