import {describe, expect, test} from 'bun:test'

import {groupByPlace} from './crumbs'

const crumb = (id: string, placeId: string | null) => ({
  id,
  place: placeId ? {id: placeId} : null,
})

describe('groupByPlace', () => {
  test('collapses crumbs sharing a place', () => {
    const groups = groupByPlace([
      crumb('a', 'p1'),
      crumb('b', 'p2'),
      crumb('c', 'p1'),
    ])
    expect(groups).toHaveLength(2)
    expect(groups[0]).toMatchObject({placeId: 'p1'})
    expect(groups[0]!.crumbs.map((c) => c.id)).toEqual(['a', 'c'])
    expect(groups[1]!.placeId).toBe('p2')
  })

  test('preserves first-seen place order', () => {
    const groups = groupByPlace([crumb('a', 'p2'), crumb('b', 'p1')])
    expect(groups.map((g) => g.placeId)).toEqual(['p2', 'p1'])
  })

  test('skips crumbs without a place', () => {
    const groups = groupByPlace([crumb('a', null), crumb('b', 'p1')])
    expect(groups).toHaveLength(1)
    expect(groups[0]!.crumbs.map((c) => c.id)).toEqual(['b'])
  })

  test('returns empty for no crumbs', () => {
    expect(groupByPlace([])).toEqual([])
  })
})
