'use strict';

const { parseNews, getNews } = require('../../src/services/newsService');

const espnFixture = {
  header: 'MLB News',
  articles: [
    {
      id: 45735348,
      type: 'Story',
      headline: 'Aaron Judge homers twice in Yankees win',
      description: 'The captain went deep in the seventh and ninth.',
      published: '2026-07-14T03:08:19Z',
      links: { web: { href: 'https://www.espn.com/mlb/story/_/id/45735348/judge' } },
      categories: [
        { type: 'league', description: 'MLB', sportId: 10 },
        { type: 'athlete', description: 'Aaron Judge', athleteId: 33192, athlete: { id: 33192, description: 'Aaron Judge' } },
        { type: 'team', description: 'New York Yankees', teamId: 10, team: { id: 10, description: 'New York Yankees', abbreviation: 'NYY' } },
      ],
    },
    {
      id: 45735111,
      type: 'HeadlineNews',
      headline: 'Commissioner addresses expansion timeline',
      description: 'League office weighs in on the next two cities.',
      published: '2026-07-13T20:00:00Z',
      links: { web: { href: 'https://www.espn.com/mlb/story/_/id/45735111/expansion' } },
      categories: [
        { type: 'league', description: 'MLB', sportId: 10 }, // NO athlete, NO team
      ],
    },
  ],
};

describe('parseNews (pure)', () => {
  test('maps ESPN articles → the contract items[]', () => {
    const items = parseNews(espnFixture);
    expect(items).toHaveLength(2);
    const a = items[0];
    expect(a.id).toBe('45735348');
    expect(a.headline).toMatch(/Aaron Judge/);
    expect(a.type).toBe('Story');
    expect(a.published).toBe('2026-07-14T03:08:19Z');
    expect(a.href).toBe('https://www.espn.com/mlb/story/_/id/45735348/judge');
  });

  test('extracts athlete + team from categories where present', () => {
    const [a] = parseNews(espnFixture);
    expect(a.athlete).toEqual({ name: 'Aaron Judge', key: expect.any(String) });
    expect(a.athlete.key).toBe('aaron judge');
    expect(a.team).toBe('New York Yankees');
  });

  test('missing athlete/team → fields ABSENT, never invented', () => {
    const items = parseNews(espnFixture);
    const noEntity = items.find((i) => i.headline.includes('expansion'));
    expect(noEntity).toBeTruthy();
    expect('athlete' in noEntity).toBe(false);
    expect('team' in noEntity).toBe(false);
  });

  test('sorts newest first by published', () => {
    const items = parseNews(espnFixture);
    expect(items[0].published > items[1].published).toBe(true);
  });

  test('empty / malformed input → []', () => {
    expect(parseNews({})).toEqual([]);
    expect(parseNews(null)).toEqual([]);
    expect(parseNews({ articles: 'nope' })).toEqual([]);
    // Article with no headline is dropped.
    expect(parseNews({ articles: [{ id: 1, description: 'x' }] })).toEqual([]);
  });
});

describe('getNews (injectable, offline)', () => {
  test('unknown sport → { sport, items: [] } without fetching', async () => {
    const axios = { get: jest.fn() };
    const out = await getNews('cricket', { axios, cacheGet: async () => null, cacheSet: async () => {} });
    expect(out).toEqual({ sport: 'cricket', items: [] });
    expect(axios.get).not.toHaveBeenCalled();
  });

  test('cache miss → fetches, parses, caches', async () => {
    const axios = { get: jest.fn().mockResolvedValue({ data: espnFixture }) };
    const cacheSet = jest.fn(async () => {});
    const out = await getNews('mlb', { axios, cacheGet: async () => null, cacheSet });
    expect(out.sport).toBe('mlb');
    expect(out.items).toHaveLength(2);
    expect(axios.get).toHaveBeenCalledTimes(1);
    expect(cacheSet).toHaveBeenCalledWith('news:mlb', { items: expect.any(Array) }, expect.any(Number));
  });

  test('cache hit → serves cache, no fetch', async () => {
    const axios = { get: jest.fn() };
    const cached = { items: [{ id: '1', headline: 'cached', published: '2026-07-14T00:00:00Z', type: 'Story', href: null, description: '' }] };
    const out = await getNews('mlb', { axios, cacheGet: async () => cached, cacheSet: async () => {} });
    expect(out.items).toEqual(cached.items);
    expect(axios.get).not.toHaveBeenCalled();
  });

  test('fetch failure → empty feed (never throws)', async () => {
    const axios = { get: jest.fn().mockRejectedValue(new Error('network')) };
    const out = await getNews('nba', { axios, cacheGet: async () => null, cacheSet: async () => {} });
    expect(out).toEqual({ sport: 'nba', items: [] });
  });
});
