import { describe, expect, it, vi } from 'vitest';

vi.mock('../../db', () => ({
  default: {
    query: vi.fn(),
    end: vi.fn(),
  },
}));

vi.mock('../weather-report', () => ({
  recoverStaleRuns: vi.fn(),
  replayTeamPropsForTeam: vi.fn(),
}));

import { isRepairTargetInWindow, parseRepairScopeFromEnv, shouldReplayTarget } from '../player-prop-floor-repair';

describe('player-prop-floor-repair', () => {
  it('parses date, leagues, and explicit target filters from env', () => {
    const scope = parseRepairScopeFromEnv({
      TARGET_DATE_ET: '2026-04-01',
      TARGET_LEAGUES: 'MLB, nba ,nhl',
      TARGET_EVENT_ID: 'mlb-cws-mia-20260401',
      TARGET_SIDE: 'home',
      TARGET_TEAM_SHORT: 'mia',
      FORCE_REPLAY_ALL: 'true',
    });

    expect(scope).toEqual({
      dateET: '2026-04-01',
      leagues: ['mlb', 'nba', 'nhl'],
      targetEventId: 'mlb-cws-mia-20260401',
      targetSide: 'home',
      targetTeamShort: 'MIA',
      forceReplayAll: true,
      useLeagueWindow: false,
    });
  });

  it('defaults to the widened league scope and league-window mode', () => {
    const scope = parseRepairScopeFromEnv({});

    expect(scope.dateET).toMatch(/^\d{4}-\d{2}-\d{2}$/);
    expect(scope.leagues).toEqual(['mlb', 'nba', 'nhl', 'epl', 'bundesliga']);
    expect(scope.targetEventId).toBeNull();
    expect(scope.targetSide).toBeNull();
    expect(scope.targetTeamShort).toBeNull();
    expect(scope.forceReplayAll).toBe(false);
    expect(scope.useLeagueWindow).toBe(true);
  });

  it('uses the same forward-window policy as the Digilander precompute path', () => {
    const now = new Date('2026-04-15T13:00:00.000Z');

    expect(isRepairTargetInWindow('epl', '2026-04-16T19:30:00.000Z', now)).toBe(true);
    expect(isRepairTargetInWindow('bundesliga', '2026-04-28T19:30:00.000Z', now)).toBe(true);
    expect(isRepairTargetInWindow('nba', '2026-04-16T19:30:00.000Z', now)).toBe(false);
  });

  it('replays under-floor teams even without explicit targeting', () => {
    expect(shouldReplayTarget({
      forceReplayAll: false,
      explicitTarget: false,
      teamPropsCount: 1,
      playerPropsCount: 2,
      minPlayerPropsPerTeam: 5,
    })).toBe(true);

    expect(shouldReplayTarget({
      forceReplayAll: false,
      explicitTarget: false,
      teamPropsCount: 1,
      playerPropsCount: 5,
      minPlayerPropsPerTeam: 5,
    })).toBe(false);
  });

  it('always replays explicit targets or force-all runs', () => {
    expect(shouldReplayTarget({
      forceReplayAll: true,
      explicitTarget: false,
      teamPropsCount: 1,
      playerPropsCount: 5,
      minPlayerPropsPerTeam: 5,
    })).toBe(true);

    expect(shouldReplayTarget({
      forceReplayAll: false,
      explicitTarget: true,
      teamPropsCount: 1,
      playerPropsCount: 5,
      minPlayerPropsPerTeam: 5,
    })).toBe(true);
  });
});
