// Wave 1 (truth-everywhere-train) — NBA/WNBA settlement.
// Locks that once a basketball grade exists, it settles against the FREE ESPN
// per-game log (espnStatsAdapter.getPlayerGameLog), records populate, the run
// is idempotent, and an unplayed/in-progress game NEVER settles. Zero network.

const svc = require('../../src/services/outcomeService');
const ledger = require('../../src/services/ledgerService');
const { statValue, nbaStatValue, logRowOnDate } = svc.__internals;

// ---- in-memory Redis (same helper shape as outcomeService.test.js) --------
function memCache(seed = {}) {
  const store = { ...seed };
  return {
    store,
    cacheGet: async (k) => (k in store ? store[k] : null),
    cacheSet: async (k, v) => { store[k] = v; return true; },
  };
}

// ESPN gamelog rows carry a FULL ISO timestamp (a late tip is 00:xxZ the next
// UTC day) — the exact shape Wave 0's getPlayerGameLog returns.
const NOW = '2026-07-13T15:00:00.000Z';        // 11am ET Jul 13 = "today"
const GRADED_TS = '2026-07-12T23:30:00.000Z';  // 7:30pm ET Jul 12 (locked pre-game)
const GAME_ISO = '2026-07-13T01:00:00.000+00:00'; // 9pm ET Jul 12 → ET date Jul 12

function snapshot(sport, grades) { return { sport, updated_at: GRADED_TS, grades }; }
function grade(over = {}) {
  return {
    player: over.player || "A'ja Wilson",
    stat_type: over.stat || 'points',
    line: over.line != null ? over.line : 19.5,
    direction: over.side || 'over',
    grade: over.grade || 'A',
    gradedAt: { line: over.line != null ? over.line : 19.5, odds: -115, timestamp: GRADED_TS },
  };
}
// espnStatsAdapter.getPlayerGameLog fixture: { found, id, last10:[{date, stat}] }
function espnLog(statObj, dateIso = GAME_ISO) {
  return { found: true, id: '3149391', last10: [{ date: dateIso, opponent: 'IND', isHome: true, stat: statObj }] };
}

describe('statValue — sport-aware (NBA/WNBA box keys, S11 three-map-split kept)', () => {
  test('MLB path unchanged when sport unspecified/mlb', () => {
    expect(statValue({ homeRuns: 1 }, 'home_runs')).toBe(1);
    expect(statValue({ homeRuns: 1 }, 'home_runs', 'mlb')).toBe(1);
  });
  test('NBA/WNBA simple stats read the ESPN box object', () => {
    const box = { points: 24, rebounds: 12, assists: 3, threes: 2, steals: 1, blocks: 1, turnovers: 4 };
    expect(statValue(box, 'points', 'wnba')).toBe(24);
    expect(statValue(box, 'rebounds', 'nba')).toBe(12);
    expect(statValue(box, 'threes', 'wnba')).toBe(2);
    expect(statValue(box, 'turnovers', 'nba')).toBe(4);
  });
  test('combo stat_types sum their components (pts_reb_ast, reb_ast, stl_blk)', () => {
    const box = { points: 20, rebounds: 12, assists: 2, steals: 1, blocks: 3 };
    expect(nbaStatValue(box, 'pts_reb_ast')).toBe(34);
    expect(nbaStatValue(box, 'pts_reb')).toBe(32);
    expect(nbaStatValue(box, 'reb_ast')).toBe(14);
    expect(nbaStatValue(box, 'stl_blk')).toBe(4);
  });
  test('a combo with a missing component never fabricates a total', () => {
    expect(nbaStatValue({ points: 20, rebounds: 12 }, 'pts_reb_ast')).toBeNull();
  });
  test('an unmapped NBA stat is unsettleable (absent beats a fabricated outcome)', () => {
    expect(statValue({ points: 20 }, 'double_doubles', 'wnba')).toBeNull();
  });
});

describe('logRowOnDate — ESPN ISO date normalized to UTC+ET', () => {
  test('MLB rows exact-compare YYYY-MM-DD (unchanged)', () => {
    expect(logRowOnDate({ date: '2026-07-09' }, '2026-07-09', 'mlb')).toBe(true);
    expect(logRowOnDate({ date: '2026-07-09' }, '2026-07-08', 'mlb')).toBe(false);
  });
  test('NBA/WNBA ISO row matches its ET date (late tip rolled past UTC midnight)', () => {
    expect(logRowOnDate({ date: GAME_ISO }, '2026-07-12', 'wnba')).toBe(true); // ET
    expect(logRowOnDate({ date: GAME_ISO }, '2026-07-13', 'nba')).toBe(true);  // UTC
    expect(logRowOnDate({ date: GAME_ISO }, '2026-07-11', 'wnba')).toBe(false);
  });
});

describe('settleSnapshot — WNBA grades settle vs the real ESPN game log', () => {
  test('a locked WNBA over settles to a hit and populates accuracy:wnba + byGrade', async () => {
    const cache = memCache({ 'snapshot:wnba:latest': snapshot('wnba', [grade({ stat: 'points', line: 19.5, side: 'over', grade: 'A' })]) });
    const getPlayerStats = async () => espnLog({ points: 24, rebounds: 12, assists: 3 });
    const res = await svc.settleSnapshot('wnba', { ...cache, getPlayerStats, now: () => NOW });
    expect(res.settled).toBe(1);
    expect(res.log[0]).toMatchObject({ result: 'hit', actual: 24, grade: 'A', side: 'O' });
    expect(cache.store['accuracy:wnba'].byGrade['A'].hits).toBe(1);
    expect(cache.store['accuracy:wnba'].overall.pct).toBe(100);
  });

  test('settles a miss (under, actual above line)', async () => {
    const cache = memCache({ 'snapshot:wnba:latest': snapshot('wnba', [grade({ stat: 'points', line: 19.5, side: 'under', grade: 'B' })]) });
    const getPlayerStats = async () => espnLog({ points: 24 });
    const res = await svc.settleSnapshot('wnba', { ...cache, getPlayerStats, now: () => NOW });
    expect(res.log[0].result).toBe('miss');
    expect(cache.store['accuracy:wnba'].byGrade['B'].misses).toBe(1);
  });

  test('settles a push (actual equals line)', async () => {
    const cache = memCache({ 'snapshot:wnba:latest': snapshot('wnba', [grade({ stat: 'points', line: 24, side: 'over', grade: 'C' })]) });
    const getPlayerStats = async () => espnLog({ points: 24 });
    const res = await svc.settleSnapshot('wnba', { ...cache, getPlayerStats, now: () => NOW });
    expect(res.log[0].result).toBe('push');
  });

  test('a combo prop (pts_reb_ast) settles', async () => {
    const cache = memCache({ 'snapshot:wnba:latest': snapshot('wnba', [grade({ stat: 'pts_reb_ast', line: 29.5, side: 'over', grade: 'A' })]) });
    const getPlayerStats = async () => espnLog({ points: 20, rebounds: 12, assists: 2 }); // 34
    const res = await svc.settleSnapshot('wnba', { ...cache, getPlayerStats, now: () => NOW });
    expect(res.settled).toBe(1);
    expect(res.log[0]).toMatchObject({ result: 'hit', actual: 34, stat: 'pts_reb_ast' });
  });

  test('idempotent — a second run does not double-count', async () => {
    const cache = memCache({ 'snapshot:wnba:latest': snapshot('wnba', [grade({ grade: 'A' })]) });
    const deps = { ...cache, getPlayerStats: async () => espnLog({ points: 24 }), now: () => NOW };
    await svc.settleSnapshot('wnba', deps);
    const res2 = await svc.settleSnapshot('wnba', deps);
    expect(res2.settled).toBe(0);
    expect(res2.log.length).toBe(1);
    expect(cache.store['accuracy:wnba'].overall.total).toBe(1);
  });

  test('an in-progress / today game does NOT settle (final-honesty guard)', async () => {
    // Graded today, ESPN returns a row whose ET date is TODAY → never settle it.
    const gradedToday = '2026-07-13T14:00:00.000Z'; // 10am ET Jul 13
    const todaysGame = '2026-07-13T23:00:00.000+00:00'; // 7pm ET Jul 13 (in progress)
    const g = grade({ stat: 'points', line: 19.5, side: 'over', grade: 'A' });
    g.gradedAt.timestamp = gradedToday;
    const cache = memCache({ 'snapshot:wnba:latest': { sport: 'wnba', updated_at: gradedToday, grades: [g] } });
    const getPlayerStats = async () => espnLog({ points: 30 }, todaysGame);
    const res = await svc.settleSnapshot('wnba', { ...cache, getPlayerStats, now: () => NOW });
    expect(res.settled).toBe(0);
    expect(res.pending).toBe(1);
  });

  test('offline ESPN (found:false) → pending, never throws', async () => {
    const cache = memCache({ 'snapshot:nba:latest': snapshot('nba', [grade()]) });
    const res = await svc.settleSnapshot('nba', { ...cache, getPlayerStats: async () => ({ found: false }), now: () => NOW });
    expect(res.settled).toBe(0);
    expect(res.pending).toBe(1);
  });
});

describe('ledgerService.settleLedger — WNBA settles vs the ESPN game log', () => {
  // Minimal chainable Supabase stub (same shape as ledgerService.test.js).
  function fakeSb() {
    const calls = { updates: [] };
    const state = { selectResults: [], selectCursor: 0, countResult: 0 };
    function builder() {
      const b = {
        _update: null,
        upsert() { return Promise.resolve({ error: null }); },
        update(v) { b._update = v; return b; },
        select() { return b; }, eq() { return b; }, is() { return b; },
        not() { return b; }, lt() { return b; }, gte() { return b; }, gt() { return b; }, order() { return b; },
        in(col, ids) {
          if (b._update) { calls.updates.push({ values: b._update, ids }); return Promise.resolve({ error: null }); }
          return terminal();
        },
        limit() { return terminal(); },
        then(res, rej) { return terminal().then(res, rej); },
      };
      function terminal() {
        if (b._update) { calls.updates.push({ values: b._update }); return Promise.resolve({ error: null }); }
        const data = state.selectResults[state.selectCursor] ?? [];
        state.selectCursor += 1;
        return Promise.resolve({ data, error: null, count: state.countResult });
      }
      return b;
    }
    return { from: () => builder(), _calls: calls, _state: state };
  }

  test('settles a WNBA row (points) via the ESPN gamelog ET-date match', async () => {
    const sb = fakeSb();
    sb._state.selectResults = [
      [{ id: 'r1' }],
      [{ id: 'r1', player_name: "A'ja Wilson", stat: 'points', line: 19.5, side: 'over', closing_line: 19.5, game_date: '2026-07-12' }],
    ];
    // ESPN ISO date normalizes to ET 2026-07-12 → matches game_date.
    const getPlayerStats = async () => espnLog({ points: 24 });
    const res = await ledger.settleLedger('wnba', { sb, getPlayerStats, now: () => NOW, beforeDate: '2026-07-13' });
    expect(res.settled).toBe(1);
    expect(sb._calls.updates[0].values).toMatchObject({ outcome: 'hit', actual_value: 24, clv: 0, clv_result: 'flat' });
  });

  test('by_tier populates for WNBA settled rows (records need no new plumbing)', async () => {
    const sb = fakeSb();
    const rows = [
      ...Array.from({ length: 14 }, () => ({ outcome: 'hit', clv_result: null, grade: 'A' })),
      ...Array.from({ length: 6 }, () => ({ outcome: 'miss', clv_result: null, grade: 'A-' })),
    ];
    sb._state.selectResults = [rows];
    sb._state.countResult = 0;
    // by_tier is sport-agnostic: once WNBA rows carry an outcome + grade they
    // flow into the SAME calibration buckets the MLB path uses (no new plumbing).
    const agg = await ledger.getModelAggregate({ sb });
    expect(agg.by_tier.A.settled).toBe(20);
    expect(agg.by_tier.A.hit_pct).toBe(70);
  });
});
