import { describe, expect, it } from 'vitest';
import { normalizeEventStartTime, reconcileStartTimeFromCurrentOdds } from '../start-time-reconciliation';
import type { TheOddsCurrentEvent } from '../the-odds';

function makeCurrentEvent(overrides: Partial<TheOddsCurrentEvent> = {}): TheOddsCurrentEvent {
  return {
    id: 'soccer-event-1',
    sport_key: 'soccer_spain_la_liga',
    sport_title: 'La Liga',
    commence_time: '2026-04-06T19:00:00Z',
    home_team: 'Girona',
    away_team: 'Villarreal',
    bookmakers: [],
    ...overrides,
  };
}

describe('start-time-reconciliation', () => {
  it('reconciles aliased events when the schedule drift is within the default window', () => {
    const result = reconcileStartTimeFromCurrentOdds({
      homeTeam: 'Girona FC',
      awayTeam: 'Villarreal',
      startsAt: '2026-04-06T18:00:00Z',
      currentEvents: [makeCurrentEvent()],
    });

    expect(result.reconciled).toBe(true);
    expect(result.startsAt).toBe('2026-04-06T19:00:00.000Z');
    expect(result.deltaMs).toBe(60 * 60 * 1000);
  });

  it('does not reconcile when the schedule drift exceeds the default window', () => {
    const result = reconcileStartTimeFromCurrentOdds({
      homeTeam: 'Girona FC',
      awayTeam: 'Villarreal',
      startsAt: '2026-04-06T16:00:00Z',
      currentEvents: [makeCurrentEvent()],
    });

    expect(result.reconciled).toBe(false);
    expect(result.startsAt).toBe('2026-04-06T16:00:00.000Z');
    expect(result.deltaMs).toBe(3 * 60 * 60 * 1000);
  });

  it('normalizes stray seconds even when no matching current event is found', () => {
    expect(normalizeEventStartTime('2026-04-06T19:10:31Z')).toBe('2026-04-06T19:10:00.000Z');

    const result = reconcileStartTimeFromCurrentOdds({
      homeTeam: 'Girona FC',
      awayTeam: 'Villarreal',
      startsAt: '2026-04-06T19:10:31Z',
      currentEvents: [],
    });

    expect(result.reconciled).toBe(false);
    expect(result.startsAt).toBe('2026-04-06T19:10:00.000Z');
    expect(result.deltaMs).toBe(null);
  });
});
