/**
 * Cross-life Hall of Fame (T8): a persistent "beat your best life" record that
 * survives every new life, so death has stakes (new record / best: X).
 */
import { describe, it, expect } from 'vitest';
import { PlayerFactory } from '../../src/testing/PlayerFactory.js';
import { handleDeath } from '../../src/services/health/health_manager.js';

/** Simulate the start of a new life for the hall-of-fame: clear the per-death
 * summary + death dedup, but (like the real reset) leave hallOfFame intact. */
function beginNewLife(player: any, age: number, money: number): void {
  player.lifeSummary = null;
  player.events.delete('death');
  player.c.status = 'alive';
  player.c.ageYears = age;
  player.c.money = money;
}

describe('Hall of Fame (cross-life personal best)', () => {
  it('records the first life as a record and seeds the best', () => {
    const p: any = PlayerFactory.createAtAge(70);
    p.c.money = 100_000;
    handleDeath(p);
    expect(p.hallOfFame.lives).toBe(1);
    expect(p.lifeSummary.isNewRecord).toBe(true);
    expect(p.hallOfFame.bestScore).toBe(p.lifeSummary.score);
    expect(p.hallOfFame.bestLife).not.toBeNull();
    expect(p.hallOfFame.recentScores).toHaveLength(1);
  });

  it('beats the best on a higher-scoring life, ignores a lower one', () => {
    const p: any = PlayerFactory.createAtAge(70);
    p.c.money = 100_000;
    handleDeath(p);
    const firstScore = p.hallOfFame.bestScore;

    // A longer, richer life → higher score → new record.
    beginNewLife(p, 95, 1_000_000);
    handleDeath(p);
    expect(p.hallOfFame.lives).toBe(2);
    expect(p.lifeSummary.isNewRecord).toBe(true);
    expect(p.hallOfFame.bestScore).toBeGreaterThan(firstScore);
    const bestAfterTwo = p.hallOfFame.bestScore;

    // A short, broke life → lower score → NOT a record, best unchanged.
    beginNewLife(p, 25, 0);
    handleDeath(p);
    expect(p.hallOfFame.lives).toBe(3);
    expect(p.lifeSummary.isNewRecord).toBe(false);
    expect(p.hallOfFame.bestScore).toBe(bestAfterTwo);
    expect(p.lifeSummary.bestScore).toBe(bestAfterTwo);
    expect(p.lifeSummary.lifeNumber).toBe(3);
  });

  it('caps recentScores at the last 5 lives', () => {
    const p: any = PlayerFactory.createAtAge(60);
    p.c.money = 50_000;
    for (let i = 0; i < 7; i++) {
      beginNewLife(p, 60 + i, 50_000 + i * 1000);
      handleDeath(p);
    }
    expect(p.hallOfFame.lives).toBe(7);
    expect(p.hallOfFame.recentScores.length).toBeLessThanOrEqual(5);
  });
});
