import { TournamentCodeSchema, type MatchDocument, } from '../global/database/schema'; import mongoose from 'mongoose'; import { TournamentCodeService } from './tournament-code.service'; type TournamentCodeServiceInternals = TournamentCodeService & { resolveRequiredSlots(match: MatchDocument): number; resolveSeriesRefForGameNumber( match: MatchDocument, gameNumber: number, ): { teamAIndex: number; teamBIndex: number }; ensureGameSchedule(match: MatchDocument): void; replaceForMatchGame(params: { communityId: mongoose.Types.ObjectId; matchId: mongoose.Types.ObjectId; gameNumber: number; }): Promise; attachPendingMatches(communityId?: mongoose.Types.ObjectId): Promise; }; function createService() { return new TournamentCodeService( {} as never, ) as unknown as TournamentCodeServiceInternals; } interface MatchOverrides { gameCount?: number; gameMode?: 'pair' | 'bracket' | 'round-robin' | 'double-elimination'; roundRobinMaxRounds?: number; participants?: Array<{ excluded?: boolean }>; teams?: Array<{ teamIndex: number }>; doubleElimination?: MatchDocument['doubleElimination']; gameSchedule?: Array<{ gameNumber: number; roundNumber?: number; teamAIndex: number; teamBIndex: number; }>; } function createMatch(overrides: MatchOverrides): MatchDocument { return { _id: new mongoose.Types.ObjectId(), status: 'in-progress', gameCount: 1, gameMode: 'pair', participants: [], teams: [], tournamentCodeIds: [], gameSchedule: [], save: jest.fn().mockResolvedValue(undefined), markModified: jest.fn(), ...overrides, } as unknown as MatchDocument; } describe('TournamentCodeService round-robin scheduling', () => { it('keeps pair slot calculation unchanged', () => { const service = createService(); const match = createMatch({ gameCount: 3, teams: Array.from({ length: 6 }, (_, index) => ({ teamIndex: index + 1, })), participants: Array.from({ length: 30 }, () => ({})), }); expect(service.resolveRequiredSlots(match)).toBe(9); expect(service.resolveSeriesRefForGameNumber(match, 1)).toEqual({ teamAIndex: 1, teamBIndex: 2, }); expect(service.resolveSeriesRefForGameNumber(match, 4)).toEqual({ teamAIndex: 3, teamBIndex: 4, }); expect(service.resolveSeriesRefForGameNumber(match, 7)).toEqual({ teamAIndex: 5, teamBIndex: 6, }); }); it('calculates round-robin slots from team pairs and per-pair game count', () => { const service = createService(); expect( service.resolveRequiredSlots( createMatch({ gameMode: 'round-robin', gameCount: 1, teams: Array.from({ length: 6 }, (_, index) => ({ teamIndex: index + 1, })), }), ), ).toBe(15); expect( service.resolveRequiredSlots( createMatch({ gameMode: 'round-robin', gameCount: 2, teams: Array.from({ length: 6 }, (_, index) => ({ teamIndex: index + 1, })), }), ), ).toBe(30); expect( service.resolveRequiredSlots( createMatch({ gameMode: 'round-robin', gameCount: 1, teams: [], participants: Array.from({ length: 30 }, () => ({})), }), ), ).toBe(15); }); it('calculates limited round-robin slots from max rounds', () => { const service = createService(); expect( service.resolveRequiredSlots( createMatch({ gameMode: 'round-robin', gameCount: 1, roundRobinMaxRounds: 3, teams: Array.from({ length: 8 }, (_, index) => ({ teamIndex: index + 1, })), }), ), ).toBe(12); }); it('uses persisted round-robin game schedule for game refs', () => { const service = createService(); const match = createMatch({ gameMode: 'round-robin', gameCount: 2, gameSchedule: [ { gameNumber: 1, roundNumber: 1, teamAIndex: 2, teamBIndex: 5 }, { gameNumber: 2, roundNumber: 1, teamAIndex: 2, teamBIndex: 5 }, { gameNumber: 3, roundNumber: 2, teamAIndex: 1, teamBIndex: 4 }, ], }); expect(service.resolveSeriesRefForGameNumber(match, 1)).toEqual({ teamAIndex: 2, teamBIndex: 5, }); expect(service.resolveSeriesRefForGameNumber(match, 3)).toEqual({ teamAIndex: 1, teamBIndex: 4, }); }); it('falls back to round-based pairs before schedule is persisted', () => { const service = createService(); const match = createMatch({ gameMode: 'round-robin', gameCount: 1, teams: Array.from({ length: 4 }, (_, index) => ({ teamIndex: index + 1, })), gameSchedule: [], }); expect(service.resolveSeriesRefForGameNumber(match, 1)).toEqual({ teamAIndex: 1, teamBIndex: 4, }); expect(service.resolveSeriesRefForGameNumber(match, 2)).toEqual({ teamAIndex: 2, teamBIndex: 3, }); }); it('creates a round-robin schedule once and leaves pair matches empty', () => { const service = createService(); const roundRobin = createMatch({ gameMode: 'round-robin', gameCount: 2, teams: Array.from({ length: 4 }, (_, index) => ({ teamIndex: index + 1, })), gameSchedule: [], }); service.ensureGameSchedule(roundRobin); expect(roundRobin.gameSchedule).toHaveLength(12); const persisted = [...roundRobin.gameSchedule]; service.ensureGameSchedule(roundRobin); expect(roundRobin.gameSchedule).toEqual(persisted); const pair = createMatch({ gameMode: 'pair', teams: Array.from({ length: 4 }, (_, index) => ({ teamIndex: index + 1, })), gameSchedule: [], }); service.ensureGameSchedule(pair); expect(pair.gameSchedule).toEqual([]); }); it('creates a double-elimination bracket from built teams', () => { const service = createService(); const match = createMatch({ gameMode: 'double-elimination', teams: Array.from({ length: 4 }, (_, index) => ({ teamIndex: index + 1, })), doubleElimination: { teamCount: 4, resetFinalEnabled: true, resetFinalCreated: false, seeds: [], bracketMatches: [], placements: {}, events: [], }, }); service.ensureGameSchedule(match); expect(match.doubleElimination?.seeds).toHaveLength(4); expect(match.doubleElimination?.bracketMatches).toHaveLength(6); expect( match.doubleElimination?.bracketMatches.filter( (bracketMatch) => bracketMatch.state === 'ready', ), ).toHaveLength(2); }); it('creates a limited round-robin schedule grouped by playable rounds', () => { const service = createService(); const roundRobin = createMatch({ gameMode: 'round-robin', gameCount: 1, roundRobinMaxRounds: 3, teams: Array.from({ length: 8 }, (_, index) => ({ teamIndex: index + 1, })), gameSchedule: [], }); service.ensureGameSchedule(roundRobin); expect(roundRobin.gameSchedule).toHaveLength(12); for (const roundNumber of [1, 2, 3]) { const round = roundRobin.gameSchedule.filter( (game) => game.roundNumber === roundNumber, ); expect(round).toHaveLength(4); expect( new Set(round.flatMap((game) => [game.teamAIndex, game.teamBIndex])) .size, ).toBe(8); } }); it('leaves legacy round-robin schedules without round numbers unchanged', () => { const service = createService(); const roundRobin = createMatch({ gameMode: 'round-robin', gameCount: 1, teams: Array.from({ length: 6 }, (_, index) => ({ teamIndex: index + 1, })), gameSchedule: [ { gameNumber: 1, teamAIndex: 2, teamBIndex: 5 }, { gameNumber: 2, teamAIndex: 1, teamBIndex: 2 }, { gameNumber: 3, teamAIndex: 4, teamBIndex: 5 }, { gameNumber: 4, teamAIndex: 1, teamBIndex: 6 }, { gameNumber: 5, teamAIndex: 5, teamBIndex: 6 }, { gameNumber: 6, teamAIndex: 4, teamBIndex: 6 }, ], }); const persisted = [...roundRobin.gameSchedule]; service.ensureGameSchedule(roundRobin); expect(roundRobin.gameSchedule).toEqual(persisted); }); it('does not expose round numbers for legacy round-robin slots', async () => { const codeFindExec = jest.fn().mockResolvedValue([]); const connectionService = { getModel: jest.fn().mockResolvedValue({ find: jest.fn().mockReturnValue({ exec: codeFindExec }), }), }; const service = new TournamentCodeService( connectionService as never, ) as unknown as TournamentCodeServiceInternals; const slots = await service.buildSlots( createMatch({ gameMode: 'round-robin', gameCount: 1, teams: Array.from({ length: 6 }, (_, index) => ({ teamIndex: index + 1, })), gameSchedule: [ { gameNumber: 1, teamAIndex: 2, teamBIndex: 5 }, { gameNumber: 2, teamAIndex: 1, teamBIndex: 2 }, { gameNumber: 3, teamAIndex: 4, teamBIndex: 5 }, { gameNumber: 4, teamAIndex: 1, teamBIndex: 6 }, { gameNumber: 5, teamAIndex: 5, teamBIndex: 6 }, { gameNumber: 6, teamAIndex: 4, teamBIndex: 6 }, { gameNumber: 7, teamAIndex: 2, teamBIndex: 6 }, { gameNumber: 8, teamAIndex: 3, teamBIndex: 5 }, { gameNumber: 9, teamAIndex: 2, teamBIndex: 3 }, { gameNumber: 10, teamAIndex: 1, teamBIndex: 4 }, { gameNumber: 11, teamAIndex: 3, teamBIndex: 6 }, { gameNumber: 12, teamAIndex: 1, teamBIndex: 3 }, { gameNumber: 13, teamAIndex: 3, teamBIndex: 4 }, { gameNumber: 14, teamAIndex: 1, teamBIndex: 5 }, { gameNumber: 15, teamAIndex: 2, teamBIndex: 4 }, ], }), ); expect(slots).toHaveLength(15); expect(slots[0]).toEqual( expect.objectContaining({ gameNumber: 1, roundNumber: undefined, teamAIndex: 2, teamBIndex: 5, }), ); expect(slots.every((slot) => slot.roundNumber === undefined)).toBe(true); }); it('does not expose fallback round-robin slots before the schedule is persisted', async () => { const service = createService(); const slots = await service.buildSlots( createMatch({ gameMode: 'round-robin', gameCount: 1, teams: Array.from({ length: 6 }, (_, index) => ({ teamIndex: index + 1, })), gameSchedule: [], }), ); expect(slots).toEqual([]); }); }); describe('TournamentCodeService bulk upload', () => { it('preserves tournament code casing at the schema layer', async () => { const connection = mongoose.createConnection(); try { const TournamentCodeModel = connection.model( 'TournamentCodeCasingSpec', TournamentCodeSchema, ); const code = new TournamentCodeModel({ code: ' AbC-12345 ', expiresAt: new Date(Date.now() + 60 * 60 * 1000), uploadedBy: new mongoose.Types.ObjectId(), }); expect(code.code).toBe('AbC-12345'); } finally { await connection.close(); } }); it('stores tournament codes with the exact casing from input', async () => { const insertMany = jest.fn().mockResolvedValue(undefined); const TournamentCodeModel = { find: jest.fn().mockReturnValue({ select: jest.fn().mockReturnValue({ lean: jest.fn().mockReturnValue({ exec: jest.fn().mockResolvedValue([]), }), }), }), insertMany, }; const connectionService = { getModel: jest.fn().mockResolvedValue(TournamentCodeModel), }; const service = new TournamentCodeService( connectionService as never, ) as unknown as TournamentCodeServiceInternals; service.attachPendingMatches = jest.fn().mockResolvedValue(0); await service.bulkUpload({ communityId: new mongoose.Types.ObjectId(), uploadedBy: new mongoose.Types.ObjectId(), codes: [ { code: ' AbC-12345 ', expiresAt: new Date(Date.now() + 60 * 60 * 1000).toISOString(), }, ], }); expect(insertMany).toHaveBeenCalledWith( [ expect.objectContaining({ code: 'AbC-12345', }), ], { ordered: false }, ); }); }); describe('TournamentCodeService pool stats', () => { it('counts only available codes that are usable beyond the expiry margin', async () => { const countDocuments = jest.fn().mockReturnValue({ exec: jest.fn().mockResolvedValue(12), }); const connectionService = { getModel: jest.fn().mockResolvedValue({ countDocuments }), }; const service = new TournamentCodeService(connectionService as never); await expect(service.countUsableAvailable()).resolves.toBe(12); expect(countDocuments).toHaveBeenCalledWith({ state: 'available', expiresAt: { $gt: expect.any(Date), }, }); }); }); describe('TournamentCodeService pending match attachment', () => { it('does not attach tournament codes before match teams are built', async () => { const invalidMatch = { ...createMatch({ status: 'team-built', teams: [], tournamentCodeIds: [], } as unknown as MatchOverrides), isModified: jest.fn().mockReturnValue(false), }; const validMatch = { ...createMatch({ status: 'team-built', teams: [ { teamIndex: 1, members: [{ userId: new mongoose.Types.ObjectId() }], }, { teamIndex: 2, members: [{ userId: new mongoose.Types.ObjectId() }], }, ], tournamentCodeIds: [], } as unknown as MatchOverrides), isModified: jest.fn().mockReturnValue(false), }; const codeId = new mongoose.Types.ObjectId(); const MatchModel = { find: jest.fn().mockReturnValue({ exec: jest.fn().mockResolvedValue([invalidMatch, validMatch]), }), findById: jest.fn().mockResolvedValue(validMatch), }; const TournamentCodeModel = { findOneAndUpdate: jest.fn().mockReturnValue({ exec: jest.fn().mockResolvedValue({ _id: codeId }), }), }; const connectionService = { getModel: jest.fn().mockImplementation((modelName: string) => { if (modelName === 'match') return Promise.resolve(MatchModel); if (modelName === 'tournamentCode') { return Promise.resolve(TournamentCodeModel); } throw new Error(`Unexpected model: ${modelName}`); }), }; const service = new TournamentCodeService(connectionService as never); const matches = await service.attachPendingMatchDocuments(); expect(matches).toEqual([validMatch]); expect(MatchModel.findById).toHaveBeenCalledTimes(1); expect(MatchModel.findById).toHaveBeenCalledWith(validMatch._id); expect(TournamentCodeModel.findOneAndUpdate).toHaveBeenCalledTimes(1); expect(validMatch.tournamentCodeIds.map((id) => id.toString())).toEqual([ codeId.toString(), ]); expect(invalidMatch.tournamentCodeIds).toEqual([]); }); }); describe('TournamentCodeService code replacement', () => { function queryResult(value: T) { return { exec: jest.fn().mockResolvedValue(value) }; } function createCode(overrides: Record) { return { _id: new mongoose.Types.ObjectId(), code: 'CODE', state: 'reserved', expiresAt: new Date(Date.now() + 60 * 60 * 1000), matchId: new mongoose.Types.ObjectId(), gameNumber: 1, reservedAt: new Date(), releasedAt: undefined, riotMatchId: undefined, save: jest.fn().mockResolvedValue(undefined), ...overrides, }; } function createReplacementFixture(params?: { currentCode?: Record | null; replacementCode?: Record | null; match?: MatchDocument; }) { const communityId = new mongoose.Types.ObjectId(); const matchId = new mongoose.Types.ObjectId(); const oldCodeId = new mongoose.Types.ObjectId(); const newCodeId = new mongoose.Types.ObjectId(); const match = params?.match ?? createMatch({ _id: matchId, communityId, status: 'in-progress', gameCount: 1, participants: Array.from({ length: 10 }, () => ({})), teams: [{ teamIndex: 1 }, { teamIndex: 2 }], tournamentCodeIds: [oldCodeId], } as unknown as MatchOverrides); const currentCode = params?.currentCode === null ? null : createCode({ _id: oldCodeId, code: 'OLD-CODE', matchId, gameNumber: 1, ...(params?.currentCode ?? {}), }); const replacementCode = params?.replacementCode === null ? null : createCode({ _id: newCodeId, code: 'NEW-CODE', matchId, gameNumber: 1, ...(params?.replacementCode ?? {}), }); const MatchModel = { findOne: jest.fn().mockReturnValue(queryResult(match)), }; const TournamentCodeModel = { findOne: jest.fn().mockReturnValue(queryResult(currentCode)), findOneAndUpdate: jest.fn().mockReturnValue(queryResult(replacementCode)), }; const connectionService = { getModel: jest.fn().mockImplementation((modelName: string) => { if (modelName === 'match') return Promise.resolve(MatchModel); if (modelName === 'tournamentCode') { return Promise.resolve(TournamentCodeModel); } throw new Error(`Unexpected model: ${modelName}`); }), }; const service = new TournamentCodeService( connectionService as never, ) as unknown as TournamentCodeServiceInternals; return { match, communityId, matchId, currentCode, replacementCode, MatchModel, TournamentCodeModel, service, }; } it('replaces a reserved code on the same game slot', async () => { const { match, communityId, matchId, currentCode, replacementCode, MatchModel, TournamentCodeModel, service, } = createReplacementFixture(); const slot = await service.replaceForMatchGame({ communityId, matchId, gameNumber: 1, }); expect(slot).toEqual( expect.objectContaining({ gameNumber: 1, teamAIndex: 1, teamBIndex: 2, code: 'NEW-CODE', state: 'reserved', }), ); expect(MatchModel.findOne).toHaveBeenCalledWith({ _id: matchId, communityId, }); expect(TournamentCodeModel.findOneAndUpdate).toHaveBeenCalledWith( expect.objectContaining({ state: 'available', region: 'kr', mapType: 'SUMMONERS_RIFT', teamSize: 5, }), expect.objectContaining({ $set: expect.objectContaining({ state: 'reserved', matchId, gameNumber: 1, }), }), expect.objectContaining({ returnDocument: 'after' }), ); expect(currentCode?.state).toBe('released'); expect(currentCode?.matchId).toBeUndefined(); expect(currentCode?.gameNumber).toBeUndefined(); expect(currentCode?.save).toHaveBeenCalled(); expect(match.tournamentCodeIds.map((id) => id.toString())).toEqual([ replacementCode?._id.toString(), ]); expect(match.save).toHaveBeenCalled(); }); it('rejects replacement after the game result is collected', async () => { const matchId = new mongoose.Types.ObjectId(); const communityId = new mongoose.Types.ObjectId(); const fixture = createReplacementFixture({ match: createMatch({ _id: matchId, communityId, status: 'in-progress', gameCount: 1, participants: Array.from({ length: 10 }, () => ({})), teams: [{ teamIndex: 1 }, { teamIndex: 2 }], tournamentCodeIds: [new mongoose.Types.ObjectId()], result: { riotMatchIds: ['KR_1'], games: [{ gameNumber: 1 }], seriesResults: [], }, } as unknown as MatchOverrides), }); await expect( fixture.service.replaceForMatchGame({ communityId, matchId, gameNumber: 1, }), ).rejects.toThrow('already has a collected result'); expect(fixture.TournamentCodeModel.findOne).not.toHaveBeenCalled(); expect(fixture.TournamentCodeModel.findOneAndUpdate).not.toHaveBeenCalled(); }); it('leaves the current code untouched when no replacement code is available', async () => { const { match, communityId, matchId, currentCode, service } = createReplacementFixture({ replacementCode: null, }); await expect( service.replaceForMatchGame({ communityId, matchId, gameNumber: 1 }), ).rejects.toThrow('No available tournament code'); expect(currentCode?.save).not.toHaveBeenCalled(); expect(match.save).not.toHaveBeenCalled(); }); });