import { migrateTournamentCodeUniqueIndexes } from './20260627-tournament-code-unique-indexes'; type Doc = Record & { _id: string }; type FakeIndex = { commitQuorum?: number | string; key: Record; maxTimeMS?: number; name: string; partialFilterExpression?: Record; unique?: boolean; }; type Projection = Record; function createDb(params: { codes?: Doc[]; indexes?: FakeIndex[]; matches?: Doc[]; missingTournamentCodeNamespace?: boolean; }) { const collections = { match: params.matches ?? [], tournamentCode: params.codes ?? [], }; const indexes = [...(params.indexes ?? [])]; const collectionNames: string[] = []; let tournamentCodeNamespaceMissing = params.missingTournamentCodeNamespace ?? false; return { collectionNames, collections, indexes, db: { collection(name: string) { collectionNames.push(name); const docs = name === 'tournamentCode' ? collections.tournamentCode : name === 'match' ? collections.match : []; return { find( filter: Record = {}, options?: { projection?: Projection }, ) { return { limit() { return { async *[Symbol.asyncIterator]() { for (const doc of docs) { if (!matchesFilter(doc, filter)) continue; yield applyProjection(doc, options?.projection); } }, }; }, }; }, async updateMany( filter: Record, update: { $pull?: Record; $set?: Record; $unset?: Record; }, ) { let matchedCount = 0; let modifiedCount = 0; for (const doc of docs) { if (!matchesFilter(doc, filter)) continue; matchedCount += 1; const before = JSON.stringify(doc); applyUpdate(doc, update); if (JSON.stringify(doc) !== before) modifiedCount += 1; } return { matchedCount, modifiedCount }; }, async indexes() { if (name === 'tournamentCode' && tournamentCodeNamespaceMissing) { const error = new Error( 'ns does not exist: lolympus.tournamentCode', ) as Error & { code: number; codeName: string }; error.code = 26; error.codeName = 'NamespaceNotFound'; throw error; } return indexes.map((index) => ({ ...index })); }, async dropIndex(name: string) { const index = indexes.findIndex((item) => item.name === name); if (index >= 0) indexes.splice(index, 1); }, async createIndex( key: Record, options: { name: string; partialFilterExpression?: Record; unique?: boolean; }, ) { if (name === 'tournamentCode') { tournamentCodeNamespaceMissing = false; } indexes.push({ key, ...options }); return options.name; }, }; }, }, }; } function matchesFilter(doc: Doc, filter: Record): boolean { const clauses = filter.$or; if (Array.isArray(clauses)) { return clauses.some((clause) => matchesFilter(doc, clause)); } return Object.entries(filter).every(([key, value]) => { if (key === '$or') return true; return matchesValue(readPath(doc, key), value); }); } function matchesValue(actual: unknown, expectedValue: unknown): boolean { if (isRecord(expectedValue)) { if ('$exists' in expectedValue) { const exists = actual !== undefined; if (exists !== expectedValue.$exists) return false; } if ('$in' in expectedValue) { const expected = (expectedValue.$in as unknown[]).map(String); if (Array.isArray(actual)) { if (!actual.some((item) => expected.includes(String(item)))) { return false; } } else if (!expected.includes(String(actual))) { return false; } } if ('$ne' in expectedValue) { if (JSON.stringify(actual) === JSON.stringify(expectedValue.$ne)) { return false; } } if ('$type' in expectedValue) { if (expectedValue.$type === 'string' && typeof actual !== 'string') { return false; } } return true; } return actual === expectedValue; } function applyUpdate( doc: Doc, update: { $pull?: Record; $set?: Record; $unset?: Record; }, ) { Object.assign(doc, update.$set ?? {}); for (const key of Object.keys(update.$unset ?? {})) { delete doc[key]; } for (const [key, pull] of Object.entries(update.$pull ?? {})) { const current = doc[key]; if (!Array.isArray(current)) continue; if (!isRecord(pull) || !('$in' in pull)) continue; const pulled = (pull.$in as unknown[]).map(String); doc[key] = current.filter((item) => !pulled.includes(String(item))); } } function applyProjection(doc: Doc, projection?: Projection): Doc { if (!projection) return doc; const projected: Doc = { _id: doc._id }; for (const [key, value] of Object.entries(projection)) { if (value !== 1 || key === '_id') continue; const actual = readPath(doc, key); if (actual !== undefined) projected[key] = actual; } return projected; } function readPath(doc: Record, path: string): unknown { const parts = path.split('.'); let current: unknown = doc; for (const part of parts) { if (Array.isArray(current) && /^\d+$/.test(part)) { current = current[Number(part)]; continue; } if (!isRecord(current)) return undefined; current = current[part]; } return current; } function isRecord(value: unknown): value is Record { return Boolean(value && typeof value === 'object' && !Array.isArray(value)); } describe('migrateTournamentCodeUniqueIndexes', () => { it('dry-runs duplicate cleanup without mutating documents or indexes', async () => { const { db, collectionNames, collections, indexes } = createDb({ codes: [ { _id: 'code-1', code: 'A', matchId: 'match-1', gameNumber: 1, reservedAt: new Date('2026-06-01T00:00:00.000Z'), state: 'reserved', }, { _id: 'code-2', code: 'B', matchId: 'match-1', gameNumber: 1, reservedAt: new Date('2026-06-02T00:00:00.000Z'), state: 'reserved', }, { _id: 'code-3', code: 'C', riotMatchId: 'KR_1', state: 'released', }, { _id: 'code-4', code: 'D', riotMatchId: 'KR_1', state: 'used', }, { _id: 'code-5', code: 'E', riotMatchId: ' ', state: 'reserved', }, ], indexes: [{ key: { riotMatchId: 1 }, name: 'riotMatchId_1' }], matches: [{ _id: 'match-1', tournamentCodeIds: ['code-1', 'code-2'] }], }); const beforeCodes = JSON.stringify(collections.tournamentCode); const beforeIndexes = JSON.stringify(indexes); const progressPhases: string[] = []; const result = await migrateTournamentCodeUniqueIndexes(db, { dryRun: true, onProgress: (progress) => progressPhases.push(progress.phase), }); expect(result.stats).toMatchObject({ blankRiotMatchIdsToUnset: 1, blankRiotMatchIdsUnset: 0, duplicateCodesReleased: 0, duplicateCodesToRelease: 2, duplicateGameNumberGroups: 1, duplicateRiotMatchGroups: 1, indexesCreated: 0, indexesDropped: 0, scannedCodes: 5, scannedMatches: 1, }); expect(result.sampleDuplicateGroups).toHaveLength(2); expect(progressPhases).toEqual( expect.arrayContaining(['scanMatches', 'scanTournamentCodes']), ); expect(collectionNames).toContain('tournamentCode'); expect(collectionNames).not.toContain('tournament_code'); expect(JSON.stringify(collections.tournamentCode)).toBe(beforeCodes); expect(JSON.stringify(indexes)).toBe(beforeIndexes); }); it('releases duplicate losers, pulls them from matches, and replaces old indexes', async () => { const now = new Date('2026-06-27T00:00:00.000Z'); const { db, collections, indexes } = createDb({ codes: [ { _id: 'code-1', code: 'A', matchId: 'match-1', gameNumber: 1, reservedAt: new Date('2026-06-01T00:00:00.000Z'), state: 'reserved', }, { _id: 'code-2', code: 'B', matchId: 'match-1', gameNumber: 1, reservedAt: new Date('2026-06-02T00:00:00.000Z'), state: 'reserved', }, { _id: 'code-3', code: 'C', riotMatchId: 'KR_1', state: 'used', }, { _id: 'code-4', code: 'D', riotMatchId: 'KR_1', state: 'released', }, { _id: 'code-5', code: 'E', riotMatchId: '', state: 'reserved', }, ], indexes: [ { key: { matchId: 1, gameNumber: 1 }, name: 'matchId_1_gameNumber_1' }, { key: { matchId: 1, bracketMatchId: 1 }, name: 'matchId_1_bracketMatchId_1', }, { key: { riotMatchId: 1 }, name: 'riotMatchId_1' }, ], matches: [{ _id: 'match-1', tournamentCodeIds: ['code-1', 'code-4'] }], }); const result = await migrateTournamentCodeUniqueIndexes(db, { dryRun: false, now, }); expect(result.stats).toMatchObject({ blankRiotMatchIdsToUnset: 1, blankRiotMatchIdsUnset: 1, duplicateCodesReleased: 2, duplicateCodesToRelease: 2, indexesCreated: 3, indexesDropped: 3, matchesUpdated: 1, }); expect( collections.tournamentCode.find((code) => code._id === 'code-2'), ).toMatchObject({ code: 'B', releasedAt: now, state: 'released', }); expect( collections.tournamentCode.find((code) => code._id === 'code-2'), ).not.toHaveProperty('matchId'); expect( collections.tournamentCode.find((code) => code._id === 'code-4'), ).not.toHaveProperty('riotMatchId'); expect( collections.tournamentCode.find((code) => code._id === 'code-5'), ).not.toHaveProperty('riotMatchId'); expect(collections.match[0].tournamentCodeIds).toEqual(['code-1']); expect(indexes).toEqual( expect.arrayContaining([ expect.objectContaining({ key: { matchId: 1, gameNumber: 1 }, name: 'matchId_1_gameNumber_1', partialFilterExpression: expect.objectContaining({ state: { $in: ['reserved', 'used'] }, }), unique: true, }), expect.objectContaining({ key: { matchId: 1, bracketMatchId: 1 }, name: 'matchId_1_bracketMatchId_1', partialFilterExpression: expect.objectContaining({ state: { $in: ['reserved', 'used'] }, }), }), expect.objectContaining({ key: { riotMatchId: 1 }, name: 'riotMatchId_1', partialFilterExpression: { riotMatchId: { $type: 'string' } }, unique: true, }), ]), ); }); it('creates indexes when the tournament code collection does not exist yet', async () => { const { db, indexes } = createDb({ missingTournamentCodeNamespace: true, }); const progress: string[] = []; const result = await migrateTournamentCodeUniqueIndexes(db, { dryRun: false, indexCommitQuorum: 1, indexMaxTimeMS: 60_000, onProgress: (event) => progress.push(`${event.action ?? ''}:${event.indexName ?? ''}`), }); expect(result.stats).toMatchObject({ duplicateCodesReleased: 0, indexesAlreadyCorrect: 0, indexesCreated: 3, indexesDropped: 0, scannedCodes: 0, scannedMatches: 0, }); expect(indexes).toEqual( expect.arrayContaining([ expect.objectContaining({ commitQuorum: 1, key: { matchId: 1, gameNumber: 1 }, maxTimeMS: 60_000, name: 'matchId_1_gameNumber_1', unique: true, }), expect.objectContaining({ key: { matchId: 1, bracketMatchId: 1 }, name: 'matchId_1_bracketMatchId_1', }), expect.objectContaining({ key: { riotMatchId: 1 }, name: 'riotMatchId_1', unique: true, }), ]), ); expect(progress).toEqual( expect.arrayContaining([ 'create:matchId_1_gameNumber_1', 'created:matchId_1_gameNumber_1', ]), ); }); it('refuses to release used duplicate losers by default', async () => { const { db, collections } = createDb({ codes: [ { _id: 'code-1', matchId: 'match-1', gameNumber: 1, state: 'used', usedAt: new Date('2026-06-01T00:00:00.000Z'), }, { _id: 'code-2', matchId: 'match-1', gameNumber: 1, state: 'used', usedAt: new Date('2026-06-02T00:00:00.000Z'), }, ], matches: [{ _id: 'match-1', tournamentCodeIds: ['code-1', 'code-2'] }], }); await expect( migrateTournamentCodeUniqueIndexes(db, { dryRun: false }), ).rejects.toThrow('Refusing to release 1 used duplicate tournament codes'); expect(collections.tournamentCode[0]).toMatchObject({ matchId: 'match-1', state: 'used', }); }); it('keeps the match-referenced slot code before state priority', async () => { const { db, collections } = createDb({ codes: [ { _id: 'code-1', code: 'USED-NOT-REFERENCED', matchId: 'match-1', gameNumber: 1, state: 'used', usedAt: new Date('2026-06-02T00:00:00.000Z'), }, { _id: 'code-2', code: 'RESERVED-REFERENCED', matchId: 'match-1', gameNumber: 1, state: 'reserved', reservedAt: new Date('2026-06-01T00:00:00.000Z'), }, ], matches: [{ _id: 'match-1', tournamentCodeIds: ['code-2'] }], }); const beforeCodes = JSON.stringify(collections.tournamentCode); const beforeMatches = JSON.stringify(collections.match); await expect( migrateTournamentCodeUniqueIndexes(db, { dryRun: false }), ).rejects.toThrow('Refusing to release 1 used duplicate tournament codes'); expect(JSON.stringify(collections.tournamentCode)).toBe(beforeCodes); expect(JSON.stringify(collections.match)).toBe(beforeMatches); }); it('allows multiple active codes for the same double-elimination bracket match', async () => { const { db, collections } = createDb({ codes: [ { _id: 'code-1', matchId: 'match-1', gameNumber: 1, bracketMatchId: 'WB_R1_M1', state: 'reserved', }, { _id: 'code-2', matchId: 'match-1', gameNumber: 2, bracketMatchId: 'WB_R1_M1', state: 'reserved', }, ], matches: [{ _id: 'match-1', tournamentCodeIds: ['code-1', 'code-2'] }], }); const result = await migrateTournamentCodeUniqueIndexes(db, { dryRun: false, createIndexes: false, }); expect(result.stats).toMatchObject({ duplicateBracketMatchGroups: 0, duplicateCodesReleased: 0, duplicateCodesToRelease: 0, }); expect(collections.tournamentCode).toEqual( expect.arrayContaining([ expect.objectContaining({ _id: 'code-1', state: 'reserved' }), expect.objectContaining({ _id: 'code-2', state: 'reserved' }), ]), ); expect(collections.match[0].tournamentCodeIds).toEqual([ 'code-1', 'code-2', ]); }); it('unsets blank riot match ids without treating them as duplicate releases', async () => { const { db, collections } = createDb({ codes: [ { _id: 'code-1', riotMatchId: '', state: 'reserved' }, { _id: 'code-2', riotMatchId: ' ', state: 'available' }, ], }); const result = await migrateTournamentCodeUniqueIndexes(db, { dryRun: false, createIndexes: false, }); expect(result.stats).toMatchObject({ blankRiotMatchIdsToUnset: 2, blankRiotMatchIdsUnset: 2, duplicateCodesReleased: 0, duplicateCodesToRelease: 0, duplicateRiotMatchGroups: 0, }); expect(collections.tournamentCode[0]).toMatchObject({ _id: 'code-1', state: 'reserved', }); expect(collections.tournamentCode[0]).not.toHaveProperty('riotMatchId'); expect(collections.tournamentCode[1]).not.toHaveProperty('riotMatchId'); }); it('allows used duplicate cleanup only when explicitly requested', async () => { const now = new Date('2026-06-27T00:00:00.000Z'); const { db, collections } = createDb({ codes: [ { _id: 'code-1', matchId: 'match-1', gameNumber: 1, state: 'used', usedAt: new Date('2026-06-01T00:00:00.000Z'), }, { _id: 'code-2', matchId: 'match-1', gameNumber: 1, state: 'used', usedAt: new Date('2026-06-02T00:00:00.000Z'), }, ], matches: [{ _id: 'match-1', tournamentCodeIds: ['code-1', 'code-2'] }], }); const result = await migrateTournamentCodeUniqueIndexes(db, { allowUsedDuplicateRelease: true, dryRun: false, now, }); expect(result.stats).toMatchObject({ duplicateCodesReleased: 1, unsafeUsedDuplicateCodes: 1, unsafeUsedDuplicateGroups: 1, }); expect(collections.tournamentCode[0]).toMatchObject({ releasedAt: now, state: 'released', }); expect(collections.tournamentCode[0]).not.toHaveProperty('usedAt'); expect(collections.match[0].tournamentCodeIds).toEqual(['code-2']); }); });