import { describe, expect, it } from 'bun:test';
import {
  buildNewsTickerCommand,
  formatNewsRelativeTime,
  highlightReasonLabel,
  newsSentimentLabel,
  newsSentimentTone,
  partitionNewsSummaryArticles,
  sortNewsArticlesChronologically,
} from './index';
import type { NewsArticle } from '../types/news';

const sampleArticles: NewsArticle[] = [
  {
    id: '3',
    sourceId: 'source-1',
    source: 'Source 1',
    headline: 'Recent neutral item',
    summary: 'Summary 3',
    publishedAt: '2026-04-08T10:00:00Z',
    publishedTs: 300,
    fetchedAt: '2026-04-08T10:01:00Z',
    sentiment: 'NEUTRAL',
    sentimentScore: 0,
    tickers: ['SPY'],
    isRead: false,
    isSaved: false,
  },
  {
    id: '2',
    sourceId: 'source-2',
    source: 'Source 2',
    headline: 'Older highlighted item',
    summary: 'Summary 2',
    publishedAt: '2026-04-08T09:00:00Z',
    publishedTs: 200,
    fetchedAt: '2026-04-08T09:01:00Z',
    sentiment: 'BULL',
    sentimentScore: 0.7,
    highlightReason: 'macro_event',
    tickers: ['AAPL'],
    isRead: false,
    isSaved: false,
  },
  {
    id: '1',
    sourceId: 'source-3',
    source: 'Source 3',
    headline: 'Newest highlighted item',
    summary: 'Summary 1',
    publishedAt: '2026-04-08T11:00:00Z',
    publishedTs: 400,
    fetchedAt: '2026-04-08T11:01:00Z',
    sentiment: 'BEAR',
    sentimentScore: -0.7,
    highlightReason: 'strong_sentiment',
    tickers: ['NVDA'],
    isRead: false,
    isSaved: false,
  },
];

describe('news formatting helpers', () => {
  it('formats recent and older relative times', () => {
    expect(
      formatNewsRelativeTime('2026-04-08T09:45:00Z', new Date('2026-04-08T10:00:00Z')),
    ).toBe('15m ago');
    expect(
      formatNewsRelativeTime('2026-04-07T10:00:00Z', new Date('2026-04-08T10:00:00Z')),
    ).toBe('1d ago');
  });

  it('maps sentiment values to terminal badge tone and label', () => {
    expect(newsSentimentTone('BULL')).toBe('bullish');
    expect(newsSentimentTone('BEAR')).toBe('bearish');
    expect(newsSentimentLabel('NEUTRAL')).toBe('Neutral');
  });

  it('maps highlight reasons to concise labels', () => {
    expect(highlightReasonLabel('macro_event')).toBe('Macro');
    expect(highlightReasonLabel('recent_high_value')).toBe('Fresh');
  });

  it('sorts articles in reverse chronological order', () => {
    expect(sortNewsArticlesChronologically(sampleArticles).map((article) => article.id)).toEqual([
      '1',
      '3',
      '2',
    ]);
  });

  it('partitions summary articles without duplicating highlighted items', () => {
    const { highlights, recent } = partitionNewsSummaryArticles(sampleArticles);

    expect(highlights.map((article) => article.id)).toEqual(['1', '2']);
    expect(recent.map((article) => article.id)).toEqual(['3']);
  });

  it('builds ticker commands from chip values', () => {
    expect(buildNewsTickerCommand(' nvda ')).toBe('/news NVDA');
  });
});
