import request from 'supertest';
const { app } = require('../src/app');
const gamesModule = require('../../server/routes/games');

// Import helpers for direct testing (exported for tests)
const { processTies } = gamesModule;

describe('Server Routes', () => {
  it('should respond to GET /', async () => {
    const response = await request(app).get('/');
    expect(response.status).toBe(200);
  });

  // Add more tests as needed
  it('resolves ties and preserves earlier rolls precedence', () => {
    /* Build fake players to simulate the scenario:
     * - James rolled 2
     * - Guest rolled 2
     * - Incognito rolled 5
     * Expectation: Incognito 1st, Guest 2nd, James 3rd
     * To simulate tie re-roll, processTies should mark ties and pad singleton orders.
     */
    const players = [
      { name: 'James', color: 'R', order: 2, orderRoll: 2, position: '', orderStatus: '', tied: false },
      { name: 'Guest', color: 'B', order: 2, orderRoll: 2, position: '', orderStatus: '', tied: false },
      { name: 'Incognito', color: 'O', order: 5, orderRoll: 5, position: '', orderStatus: '', tied: false },
    ];

    // First sort like the server does (descending by order)
    players.sort((A: any, B: any) => B.order - A.order);

    // Invoke processTies to simulate the server behavior
    const hadTies = processTies(players as any);

    // There should be ties among the two players who rolled 2
    expect(hadTies).toBe(true);

    // Incognito should be placed 1st and not tied
  const inc = players.find((p: any) => p.name === 'Incognito');
  expect(inc).toBeDefined();
  expect(inc!.position).toBe('1st');
  expect(inc!.tied).toBe(false);

    // The two players who tied should have been marked tied and have orderRoll reset
  const james = players.find((p: any) => p.name === 'James');
  const guest = players.find((p: any) => p.name === 'Guest');
  expect(james).toBeDefined();
  expect(guest).toBeDefined();
  expect(james!.tied).toBe(true);
  expect(guest!.tied).toBe(true);
  expect(james!.orderRoll).toBe(0);
  expect(guest!.orderRoll).toBe(0);
  });
});