import { Types } from 'mongoose'; import { ConnectionService } from '../global/database/connection.service'; import { CompetitionBootstrapError, CompetitionBootstrapService, type CompetitionBootstrapMatch, } from './competition-bootstrap.service'; describe('CompetitionBootstrapService', () => { it('creates a deterministic paired-Series Competition and immutable snapshots', async () => { const firstHarness = createHarness(); const firstService = new CompetitionBootstrapService( firstHarness.connectionService as ConnectionService, ); const match = matchSnapshot({ gameMode: 'pair', teamCount: 2 }); const first = await firstService.bootstrap(match); const inserted = firstHarness.insertedPayloads[0]; expect(inserted).toMatchObject({ _id: expect.any(Types.ObjectId), matchId: MATCH_ID, communityId: COMMUNITY_ID, schemaVersion: 1, projectorVersion: 1, revision: 0, phase: 'ready', format: { type: 'paired-series', rule: { type: 'fixed-games', gameCount: 3, drawPolicy: 'allow' }, }, }); expect(inserted.teams).toEqual([ expect.objectContaining({ teamId: expect.any(Types.ObjectId), legacyTeamIndex: 1, displayOrder: 1, seedNumber: 1, name: 'Team 1', members: [ expect.objectContaining({ userId: USER_IDS[0], displayName: 'Player 1#KR1', gameName: 'Player 1', tagLine: 'KR1', profileIconId: 101, assignedPosition: 'TOP', cost: 10, }), ], }), expect.objectContaining({ teamId: expect.any(Types.ObjectId), legacyTeamIndex: 2, displayOrder: 2, seedNumber: 2, name: 'Team 2', }), ]); expect(inserted.seriesGraph).toHaveLength(1); expect(inserted.seriesGraph[0]).toMatchObject({ code: 'PAIR_M1', slots: [ { position: 'A', source: { type: 'team', teamId: inserted.teams[0].teamId.toString(), }, }, { position: 'B', source: { type: 'team', teamId: inserted.teams[1].teamId.toString(), }, }, ], }); expect(inserted.projection).toMatchObject({ competitionId: inserted._id.toString(), sourceRevision: 0, projectorVersion: 1, formatType: 'paired-series', phase: 'ready', }); expect(first._id).toEqual(inserted._id); const secondHarness = createHarness(); const secondService = new CompetitionBootstrapService( secondHarness.connectionService as ConnectionService, ); await secondService.bootstrap({ ...match, teams: [...match.teams].reverse(), participants: [...match.participants].reverse(), }); const secondInserted = secondHarness.insertedPayloads[0]; expect(secondInserted._id).toEqual(inserted._id); expect(secondInserted.teams.map(({ teamId }) => teamId)).toEqual( inserted.teams.map(({ teamId }) => teamId), ); expect(secondInserted.seriesGraph).toEqual(inserted.seriesGraph); }); it('maps round-robin configuration and preserves a limited round count', async () => { const harness = createHarness(); const service = new CompetitionBootstrapService( harness.connectionService as ConnectionService, ); await service.bootstrap( matchSnapshot({ gameMode: 'round-robin', teamCount: 4, gameCount: 2, roundRobinMaxRounds: 2, }), ); expect(harness.insertedPayloads[0]).toMatchObject({ format: { type: 'round-robin', rule: { type: 'fixed-games', gameCount: 2, drawPolicy: 'allow' }, maxRounds: 2, tieBreakers: ['series-wins', 'game-diff', 'head-to-head'], }, }); expect(harness.insertedPayloads[0].seriesGraph).toHaveLength(4); }); it('maps double elimination seeds and stage-specific Series rules', async () => { const harness = createHarness(); const service = new CompetitionBootstrapService( harness.connectionService as ConnectionService, ); const match = matchSnapshot({ gameMode: 'double-elimination', teamCount: 4, gameCount: 5, }); match.doubleElimination = { teamCount: 4, resetFinalEnabled: true, seeds: [ { seedNumber: 1, teamIndex: 3 }, { seedNumber: 2, teamIndex: 1 }, { seedNumber: 3, teamIndex: 4 }, { seedNumber: 4, teamIndex: 2 }, ], }; await service.bootstrap(match); const inserted = harness.insertedPayloads[0]; expect(inserted.format).toEqual({ type: 'double-elimination', teamCount: 4, resetFinalEnabled: true, rules: { upper: { type: 'first-to', winsRequired: 3, maxGames: 5 }, lower: { type: 'first-to', winsRequired: 1, maxGames: 1 }, grandFinal: { type: 'first-to', winsRequired: 1, maxGames: 1 }, resetFinal: { type: 'first-to', winsRequired: 1, maxGames: 1 }, }, }); expect( inserted.teams.map(({ legacyTeamIndex, seedNumber }) => ({ legacyTeamIndex, seedNumber, })), ).toEqual([ { legacyTeamIndex: 1, seedNumber: 2 }, { legacyTeamIndex: 2, seedNumber: 4 }, { legacyTeamIndex: 3, seedNumber: 1 }, { legacyTeamIndex: 4, seedNumber: 3 }, ]); expect( inserted.seriesGraph.find(({ code }) => code === 'WB_R1_M1').rule, ).toEqual({ type: 'first-to', winsRequired: 3, maxGames: 5 }); expect( inserted.seriesGraph.find(({ code }) => code?.startsWith('LB_')).rule, ).toEqual({ type: 'first-to', winsRequired: 1, maxGames: 1 }); expect(inserted.seriesGraph.find(({ code }) => code === 'GF').rule).toEqual( { type: 'first-to', winsRequired: 1, maxGames: 1 }, ); expect( inserted.seriesGraph.find(({ code }) => code === 'GF_RESET'), ).toMatchObject({ rule: { type: 'first-to', winsRequired: 1, maxGames: 1 }, activation: { type: 'grand-final-reset-required' }, }); }); it('rejects double elimination until authoritative seeds are persisted', async () => { const harness = createHarness(); const service = new CompetitionBootstrapService( harness.connectionService as ConnectionService, ); await expect( service.bootstrap( matchSnapshot({ gameMode: 'double-elimination', teamCount: 4, gameCount: 3, }), ), ).rejects.toMatchObject({ code: 'INVALID_MATCH_TEAM_SNAPSHOT', httpStatus: 422, }); expect(harness.connectionService.createSession).not.toHaveBeenCalled(); expect(harness.competitionModel.findOneAndUpdate).not.toHaveBeenCalled(); }); it('rejects incomplete and duplicate team assignments before opening a transaction', async () => { const cases: Array<[string, (match: CompetitionBootstrapMatch) => void]> = [ [ 'the Match lifecycle is still recruiting', (match) => { match.status = 'recruiting'; }, ], [ 'an active participant is not assigned', (match) => { match.teams[1].members = []; }, ], [ 'the same team index is repeated', (match) => { match.teams[1].teamIndex = match.teams[0].teamIndex; }, ], [ 'one member is assigned to multiple teams', (match) => { match.teams[1].members[0].userId = match.teams[0].members[0].userId; }, ], [ 'a team member has no participant snapshot', (match) => { match.teams[1].members[0].userId = new Types.ObjectId(); }, ], ]; for (const [label, mutate] of cases) { const harness = createHarness(); const service = new CompetitionBootstrapService( harness.connectionService as ConnectionService, ); const match = matchSnapshot({ gameMode: 'pair', teamCount: 2 }); mutate(match); await expect(service.bootstrap(match)).rejects.toMatchObject({ name: 'CompetitionBootstrapError', code: 'INVALID_MATCH_TEAM_SNAPSHOT', httpStatus: 422, }); expect(harness.connectionService.createSession).not.toHaveBeenCalled(); expect(harness.competitionModel.findOneAndUpdate).not.toHaveBeenCalled(); expect(label).toBeTruthy(); } }); it('rejects bracket mode live but explicitly maps it for legacy migration', async () => { const liveHarness = createHarness(); const liveService = new CompetitionBootstrapService( liveHarness.connectionService as ConnectionService, ); const match = matchSnapshot({ gameMode: 'bracket', teamCount: 2 }); await expect(liveService.bootstrap(match)).rejects.toEqual( expect.objectContaining>({ code: 'UNSUPPORTED_LIVE_MATCH_MODE', httpStatus: 422, }), ); const migrationHarness = createHarness(); const migrationService = new CompetitionBootstrapService( migrationHarness.connectionService as ConnectionService, ); await migrationService.bootstrap(match, { source: 'legacy-migration' }); expect(migrationHarness.insertedPayloads[0].format.type).toBe( 'paired-series', ); }); it('upserts once and links only an unlinked or already-linked Match in one transaction', async () => { const harness = createHarness(); const service = new CompetitionBootstrapService( harness.connectionService as ConnectionService, ); const competition = await service.bootstrap( matchSnapshot({ gameMode: 'pair', teamCount: 2 }), ); expect(harness.competitionModel.findOneAndUpdate).toHaveBeenCalledWith( { matchId: MATCH_ID }, { $setOnInsert: harness.insertedPayloads[0] }, expect.objectContaining({ upsert: true, returnDocument: 'after', setDefaultsOnInsert: true, session: harness.sessions[0], }), ); expect(harness.matchModel.updateOne).toHaveBeenCalledWith( { _id: MATCH_ID, status: 'team-built', teamBuiltAt: new Date('2026-07-12T00:05:00.000Z'), $or: [ { competitionId: { $exists: false } }, { competitionId: null }, { competitionId: competition._id }, ], }, { $set: { competitionId: competition._id } }, { session: harness.sessions[0] }, ); expect(harness.sessions[0].commitTransaction).toHaveBeenCalledTimes(1); expect(harness.sessions[0].abortTransaction).not.toHaveBeenCalled(); expect(harness.sessions[0].endSession).toHaveBeenCalledTimes(1); }); it('reuses an existing Competition without replacing its immutable snapshot', async () => { const existingId = new Types.ObjectId('64b000000000000000000099'); const existing = { _id: existingId, matchId: MATCH_ID, teams: [{ name: 'Original immutable team snapshot' }], revision: 4, }; const harness = createHarness({ existingCompetition: existing }); const service = new CompetitionBootstrapService( harness.connectionService as ConnectionService, ); const result = await service.bootstrap( matchSnapshot({ gameMode: 'pair', teamCount: 2 }), ); expect(result).toBe(existing); expect(harness.competitionModel.findOneAndUpdate.mock.calls[0][1]).toEqual({ $setOnInsert: harness.insertedPayloads[0], }); expect(harness.matchModel.updateOne.mock.calls[0][1]).toEqual({ $set: { competitionId: existingId }, }); }); it('retries a duplicate-key bootstrap race and safely converges on the winner', async () => { const duplicateKey = Object.assign(new Error('duplicate key'), { code: 11000, }); const winner = { _id: new Types.ObjectId('64b000000000000000000098'), matchId: MATCH_ID, revision: 0, }; const harness = createHarness({ competitionResults: [duplicateKey, winner], sessionCount: 2, }); const service = new CompetitionBootstrapService( harness.connectionService as ConnectionService, ); const result = await service.bootstrap( matchSnapshot({ gameMode: 'pair', teamCount: 2 }), ); expect(result).toBe(winner); expect(harness.connectionService.createSession).toHaveBeenCalledTimes(2); expect(harness.sessions[0].abortTransaction).toHaveBeenCalledTimes(1); expect(harness.sessions[0].commitTransaction).not.toHaveBeenCalled(); expect(harness.sessions[0].endSession).toHaveBeenCalledTimes(1); expect(harness.sessions[1].commitTransaction).toHaveBeenCalledTimes(1); expect(harness.matchModel.updateOne).toHaveBeenCalledTimes(1); }); it('aborts when the Match is already linked to a different Competition', async () => { const harness = createHarness({ matchUpdateResult: { matchedCount: 0 } }); const service = new CompetitionBootstrapService( harness.connectionService as ConnectionService, ); await expect( service.bootstrap(matchSnapshot({ gameMode: 'pair', teamCount: 2 })), ).rejects.toMatchObject({ code: 'MATCH_COMPETITION_LINK_CONFLICT', httpStatus: 409, }); expect(harness.sessions[0].abortTransaction).toHaveBeenCalledTimes(1); expect(harness.sessions[0].commitTransaction).not.toHaveBeenCalled(); }); }); const MATCH_ID = new Types.ObjectId('64b000000000000000000001'); const COMMUNITY_ID = new Types.ObjectId('64b000000000000000000002'); const USER_IDS = Array.from( { length: 8 }, (_, index) => new Types.ObjectId( `64b0000000000000000001${String(index + 1).padStart(2, '0')}`, ), ); function matchSnapshot(params: { gameMode: CompetitionBootstrapMatch['gameMode']; teamCount: number; gameCount?: number; roundRobinMaxRounds?: number; }): CompetitionBootstrapMatch { const participants = USER_IDS.slice(0, params.teamCount).map( (userId, index) => ({ userId, gameName: `Player ${index + 1}`, tagLine: 'KR1', profileIconId: 101 + index, preferredPositions: [], joinedAt: new Date('2026-07-12T00:00:00.000Z'), }), ); return { _id: MATCH_ID, communityId: COMMUNITY_ID, status: 'team-built', teamBuiltAt: new Date('2026-07-12T00:05:00.000Z'), gameCount: params.gameCount ?? 3, gameMode: params.gameMode, ...(params.roundRobinMaxRounds === undefined ? {} : { roundRobinMaxRounds: params.roundRobinMaxRounds }), participants, teams: participants.map((participant, index) => ({ teamIndex: index + 1, name: `Team ${index + 1}`, captainUserId: participant.userId, members: [ { userId: participant.userId, assignedPosition: 'TOP', cost: 10 + index, }, ], })), }; } interface InsertPayload { _id: Types.ObjectId; teams: Array<{ teamId: Types.ObjectId; legacyTeamIndex: number; seedNumber: number; }>; seriesGraph: Array<{ code?: string; rule: unknown }>; [key: string]: any; } function createHarness( options: { existingCompetition?: Record; competitionResults?: Array | Error>; matchUpdateResult?: { matchedCount: number }; sessionCount?: number; } = {}, ) { const sessions = Array.from( { length: options.sessionCount ?? 1 }, createSession, ); const insertedPayloads: InsertPayload[] = []; let competitionCall = 0; const competitionModel = { findOneAndUpdate: jest.fn( ( _filter: unknown, update: { $setOnInsert: InsertPayload }, _queryOptions: unknown, ) => { insertedPayloads.push(update.$setOnInsert); const selected = options.competitionResults?.[competitionCall++]; if (selected instanceof Error) return rejectedQuery(selected); return queryResult( selected ?? options.existingCompetition ?? update.$setOnInsert, ); }, ), }; const matchModel = { updateOne: jest .fn() .mockResolvedValue(options.matchUpdateResult ?? { matchedCount: 1 }), }; const models: Record = { competition: competitionModel, match: matchModel, }; let sessionIndex = 0; const connectionService = { createSession: jest.fn(() => Promise.resolve(sessions[sessionIndex++])), getModel: jest.fn((name: string) => Promise.resolve(models[name])), }; return { sessions, insertedPayloads, competitionModel, matchModel, connectionService, }; } function createSession() { return { startTransaction: jest.fn(), commitTransaction: jest.fn().mockResolvedValue(undefined), abortTransaction: jest.fn().mockResolvedValue(undefined), endSession: jest.fn().mockResolvedValue(undefined), }; } function queryResult(value: T) { return { exec: jest.fn().mockResolvedValue(value) }; } function rejectedQuery(error: Error) { return { exec: jest.fn().mockRejectedValue(error) }; }