// Session 47 — Phase 3: ticker keeps only the latest SCAN per sport.

const svc = require('../../src/services/snapshotService');

function memCache(initial) {
  const store = { 'ticker:items': initial || null };
  return { store, cacheGet: async (k) => store[k] ?? null, cacheSet: async (k, v) => { store[k] = v; } };
}

describe('pushTickerItems — SCAN dedup', () => {
  it('replaces a prior SCAN for the same sport (only one MLB SCAN)', async () => {
    const cache = memCache([
      { tag: 'READ', sport: 'mlb', text: 'MLB slate read · 20 props graded' },
      { tag: 'MOVE', text: 'Judge o2.5 → o3.5 ▲+1' },
    ]);
    await svc.pushTickerItems([{ tag: 'READ', sport: 'mlb', text: 'MLB slate read · 25 props graded' }], cache);
    const items = cache.store['ticker:items'];
    expect(items.filter((e) => e.tag === 'READ' && e.sport === 'mlb')).toHaveLength(1);
    expect(items.find((e) => e.tag === 'READ').text).toContain('25 props');
  });

  it('preserves MOVE/GRADE events and other sports', async () => {
    const cache = memCache([
      { tag: 'MOVE', text: 'move 1' },
      { tag: 'A+', text: 'BOMBER graded A+' },
      { tag: 'READ', sport: 'nba', text: 'NBA slate read · 10 props graded' },
    ]);
    await svc.pushTickerItems([{ tag: 'READ', sport: 'mlb', text: 'MLB slate read · 25 props graded' }], cache);
    const items = cache.store['ticker:items'];
    expect(items.find((e) => e.tag === 'MOVE')).toBeTruthy();
    expect(items.find((e) => e.tag === 'A+')).toBeTruthy();
    expect(items.find((e) => e.tag === 'READ' && e.sport === 'nba')).toBeTruthy();
  });

  it('dedupes legacy SCAN items that lack a sport field (parse from text)', async () => {
    const cache = memCache([{ tag: 'READ', text: 'MLB slate read · 20 props graded' }]);
    await svc.pushTickerItems([{ tag: 'READ', sport: 'mlb', text: 'MLB slate read · 25 props graded' }], cache);
    expect(cache.store['ticker:items'].filter((e) => e.tag === 'READ')).toHaveLength(1);
  });

  it('stays capped at 50 items', async () => {
    const many = Array.from({ length: 60 }, (_, i) => ({ tag: 'MOVE', text: `m${i}` }));
    const cache = memCache(many);
    await svc.pushTickerItems([{ tag: 'READ', sport: 'mlb', text: 'read' }], cache);
    expect(cache.store['ticker:items'].length).toBeLessThanOrEqual(50);
  });
});
