import { describe, expect, it } from 'vitest';
import { createSession, reduce, type GameState } from '../src/index';
import { T0 } from './helpers';

function session(): GameState {
  return createSession({ sessionId: 's1', eventId: 'e1', venueId: 'v1', roomId: 'r1', mode: 'ALWAYS_ON', now: T0 });
}

describe('team resolution inside the serial command', () => {
  it('friends joining at the same moment with the same new team name land on one team', () => {
    // The server mints a fresh team id per join before it knows about the other joins in flight.
    let s = session();
    s = reduce(s, { type: 'JOIN', now: T0, player: { id: 'p1', nickname: 'Ava' }, team: { id: 'team-a', name: 'Table Nine' } }).state;
    const second = reduce(s, { type: 'JOIN', now: T0 + 1, player: { id: 'p2', nickname: 'Ben' }, team: { id: 'team-b', name: '  table   NINE ' } });
    s = second.state;
    expect(Object.keys(s.teams)).toEqual(['team-a']);
    expect(s.players.p2?.teamId).toBe('team-a');
    expect(second.events.some((e) => e.type === 'TeamCreated')).toBe(false);
  });

  it('SET_TEAM to an existing name joins that team instead of creating a duplicate', () => {
    let s = session();
    s = reduce(s, { type: 'JOIN', now: T0, player: { id: 'p1', nickname: 'Ava' }, team: { id: 'team-a', name: 'Quiz Kids' } }).state;
    s = reduce(s, { type: 'JOIN', now: T0, player: { id: 'p2', nickname: 'Ben' } }).state;
    s = reduce(s, { type: 'SET_TEAM', now: T0, playerId: 'p2', team: { id: 'other-id', name: 'quiz kids' } }).state;
    expect(Object.keys(s.teams)).toHaveLength(1);
    expect(s.players.p2?.teamId).toBe('team-a');
  });
});
