import { describe, expect, it } from 'vitest';
import { pickResultDataset, pickSourceDataset } from './result-data';

describe('pickResultDataset', () => {
  it('prefers the most-downstream transform output over the source', () => {
    expect(pickResultDataset(['source_0', 'data_0', 'marks', 'root'])).toBe('data_0');
  });

  it('picks the highest data_<n> numerically, not lexically', () => {
    expect(pickResultDataset(['source_0', 'data_0', 'data_1', 'data_2'])).toBe('data_2');
    // 10 must beat 2 — guards against string ordering ('data_10' < 'data_2').
    expect(pickResultDataset(['data_2', 'data_10', 'data_9'])).toBe('data_10');
  });

  it('falls back to the most-downstream source when there is no data_<n>', () => {
    expect(pickResultDataset(['source_0', 'source_1', 'marks'])).toBe('source_1');
  });

  it('ignores dataflow internals when choosing', () => {
    expect(pickResultDataset(['root', 'marks', 'layout', 'cell', 'source_0'])).toBe('source_0');
    expect(pickResultDataset(['brush_store', '_facet', 'a:b', 'data_0'])).toBe('data_0');
  });

  it('returns a remaining non-internal table when no source/data convention matches', () => {
    expect(pickResultDataset(['root', 'marks', 'my_named_source'])).toBe('my_named_source');
  });

  it('returns null when nothing is inspectable', () => {
    expect(pickResultDataset([])).toBeNull();
    expect(pickResultDataset(['root', 'marks', 'layout', 'brush_store'])).toBeNull();
  });
});

describe('pickSourceDataset', () => {
  it('prefers the most-upstream source — the input before transforms', () => {
    expect(pickSourceDataset(['source_0', 'source_1', 'data_0', 'data_1'])).toBe('source_0');
  });

  it('picks the lowest source_<n> numerically', () => {
    expect(pickSourceDataset(['source_2', 'source_10', 'source_1'])).toBe('source_1');
  });

  it('falls back to the earliest transform stage when there is no source_<n>', () => {
    expect(pickSourceDataset(['data_0', 'data_1', 'marks'])).toBe('data_0');
  });

  it('equals the result when a spec has no transforms (only a source)', () => {
    const names = ['source_0', 'marks', 'root'];
    expect(pickSourceDataset(names)).toBe('source_0');
    expect(pickResultDataset(names)).toBe('source_0');
  });

  it('returns null when nothing is inspectable', () => {
    expect(pickSourceDataset(['root', 'marks', 'brush_store'])).toBeNull();
  });
});
