import { readFileSync } from 'node:fs'; import mongoose from 'mongoose'; import type { CompetitionBootstrapService } from '../competition/competition-bootstrap.service'; import type { CompetitionCommandService } from '../competition/competition-command.service'; import type { MatchStatsService } from '../community-stats/match-stats.service'; import type { CommunityStatsService } from '../community-stats/community-stats.service'; import type { ConnectionService } from '../global/database/connection.service'; import type { DistributedLockService } from '../global/redis/distributed-lock.service'; import type { RedisService } from '../global/redis/redis.service'; import type { RiotMatchService } from '../riot/riot-match.service'; import type { RiotMatchDto } from '../riot/riot.types'; import { LegacyImportService } from './legacy-import.service'; import type { LegacyUserSnapshot, UserByPuuidMap } from './match-builder.util'; import type { LegacyImportMemberJob } from './legacy-import.types'; const ServiceConstructor = LegacyImportService as unknown as new ( ...dependencies: unknown[] ) => LegacyImportService; describe('Legacy import Competition result cutover', () => { it('has no production Match.result writer', () => { const source = readFileSync( require.resolve('./legacy-import.service'), 'utf8', ); expect(source).not.toMatch(/\b(?:match|update)\.result\s*=/u); expect(source).not.toMatch(/\bresult\s*:\s*\{\s*winnerTeamIndex/u); }); it('creates a paired Competition and accepts Riot evidence without writing Match.result', async () => { const fixture = createImportFixture(); const competitionFactModel = { exists: jest.fn().mockResolvedValue(null), }; const matchModel = { findOneAndUpdate: jest.fn().mockReturnValue(execResult(fixture.match)), updateOne: jest.fn().mockReturnValue(execResult({ modifiedCount: 1 })), }; const connectionService = { getModel: jest.fn(async (name: string) => { if (name === 'competitionFact') return competitionFactModel; if (name === 'match') return matchModel; throw new Error(`Unexpected model ${name}`); }), } as unknown as ConnectionService; const bootstrapService = { bootstrap: jest.fn().mockResolvedValue(fixture.competition), } as unknown as jest.Mocked; const commandService = { acceptGame: jest.fn().mockResolvedValue({ competition: { ...fixture.competition, revision: 1, phase: 'completed', }, commandId: 'command-1', revision: 1, replayed: false, }), } as unknown as jest.Mocked; const matchStatsService = { buildAndUpsert: jest.fn().mockResolvedValue(undefined), } as unknown as jest.Mocked; const service = createService({ connectionService, matchStatsService, bootstrapService, commandService, runWithLock: async (_options, operation) => operation(), }); jest .spyOn( service as unknown as { ensureRiotMatchPersisted: ( riotMatchId: string, region: string, ) => Promise; }, 'ensureRiotMatchPersisted', ) .mockResolvedValue(fixture.detail); const outcome = await importSingleMatch( service, fixture.detail.metadata.matchId, fixture.job, fixture.userByPuuid, ); expect(outcome).toBe('imported'); expect(matchModel.findOneAndUpdate).toHaveBeenCalledWith( { _id: expect.any(mongoose.Types.ObjectId) }, { $setOnInsert: expect.not.objectContaining({ result: expect.anything(), doubleElimination: expect.anything(), }), }, expect.objectContaining({ upsert: true, returnDocument: 'after' }), ); expect(bootstrapService.bootstrap).toHaveBeenCalledWith( expect.objectContaining({ gameMode: 'pair', gameCount: 1, teams: expect.arrayContaining([ expect.objectContaining({ teamIndex: 1 }), expect.objectContaining({ teamIndex: 2 }), ]), }), ); expect(commandService.acceptGame).toHaveBeenCalledWith( expect.objectContaining({ competitionId: fixture.competition._id.toString(), expectedRevision: 0, evidence: expect.objectContaining({ type: 'riot', riotMatchId: fixture.detail.metadata.matchId, payloadHash: expect.stringMatching(/^[a-f0-9]{64}$/u), }), mapping: expect.objectContaining({ blueTeamId: fixture.blueTeamId.toString(), redTeamId: fixture.redTeamId.toString(), winnerTeamId: fixture.blueTeamId.toString(), algorithmVersion: 'roster-overlap-v1', mappingVersion: 1, confidence: 1, diagnostics: { trustedOverlap: 10, normalOverlap: 10, reversedOverlap: 0, }, participantAssignments: expect.any(Array), snapshot: expect.any(Object), }), }), ); expect(matchModel.updateOne).toHaveBeenCalledWith( { _id: fixture.match._id }, { $set: { status: 'finished' } }, ); expect(matchStatsService.buildAndUpsert).toHaveBeenCalledWith( fixture.match._id, { sourceRevision: 1 }, ); }); it('detects duplicates from accepted Competition fact evidence before fetching Riot data', async () => { const fixture = createImportFixture(); const competitionFactModel = { exists: jest .fn() .mockResolvedValue({ _id: new mongoose.Types.ObjectId() }), }; const connectionService = { getModel: jest.fn(async (name: string) => { if (name === 'competitionFact') return competitionFactModel; throw new Error(`Unexpected model ${name}`); }), } as unknown as ConnectionService; const service = createService({ connectionService, runWithLock: async (_options, operation) => operation(), }); const ensureRiotMatchPersisted = jest .spyOn( service as unknown as { ensureRiotMatchPersisted: () => Promise; }, 'ensureRiotMatchPersisted', ) .mockResolvedValue(fixture.detail); const outcome = await importSingleMatch( service, fixture.detail.metadata.matchId, fixture.job, fixture.userByPuuid, ); expect(outcome).toBe('duplicate'); expect(competitionFactModel.exists).toHaveBeenCalledWith({ type: 'game-accepted', 'evidence.type': 'riot', 'evidence.riotMatchId': fixture.detail.metadata.matchId, }); expect(ensureRiotMatchPersisted).not.toHaveBeenCalled(); }); it('lists new legacy imports from Competition projection when Match.result is absent', async () => { const fixture = createImportFixture(); const canonicalCompetition = { ...fixture.competition, revision: 1, phase: 'completed', projection: { phase: 'completed', series: [ { ...fixture.competition.projection.series[0], status: 'completed', entries: [ { slot: 'A', teamId: fixture.blueTeamId, gameWins: 1, }, { slot: 'B', teamId: fixture.redTeamId, gameWins: 0 }, ], outcome: { type: 'played', winnerTeamId: fixture.blueTeamId, loserTeamId: fixture.redTeamId, }, }, ], gameSlots: [], games: [ { seriesId: fixture.competition.projection.series[0].seriesId, winnerTeamId: fixture.blueTeamId, evidence: { type: 'riot', riotMatchId: fixture.detail.metadata.matchId, }, participants: fixture.match.participants.map(({ userId }) => ({ userId, })), }, ], }, }; const matchModel = { find: jest.fn().mockReturnValue({ sort: jest.fn().mockReturnValue({ limit: jest.fn().mockReturnValue(execResult([fixture.match])), }), }), }; const competitionModel = { find: jest.fn().mockReturnValue({ lean: jest.fn().mockReturnValue(execResult([canonicalCompetition])), }), }; const riotMatchModel = { find: jest.fn().mockReturnValue({ lean: jest.fn().mockReturnValue( execResult([ { matchId: fixture.detail.metadata.matchId, raw: fixture.detail, }, ]), ), }), }; const connectionService = { getModel: jest.fn((name: string) => { if (name === 'match') return Promise.resolve(matchModel); if (name === 'competition') return Promise.resolve(competitionModel); if (name === 'riotMatch') return Promise.resolve(riotMatchModel); return Promise.reject(new Error(`Unexpected model ${name}`)); }), } as unknown as ConnectionService; const service = createService({ connectionService }); jest .spyOn( service as unknown as { buildUserByPuuidMap: () => Promise; }, 'buildUserByPuuidMap', ) .mockResolvedValue(fixture.userByPuuid); const page = await service.listLegacyMatches({ communityId: fixture.match.communityId, }); expect(page.matches).toEqual([ expect.objectContaining({ matchId: fixture.match._id.toString(), riotMatchId: fixture.detail.metadata.matchId, memberCount: 10, externalCount: 0, teamAIndex: 1, teamBIndex: 2, teamAWins: 1, teamBWins: 0, winnerTeamIndex: 1, }), ]); }); it('cascades admin deletion through Competition facts and read models', async () => { const fixture = createImportFixture(); const session = { startTransaction: jest.fn(), commitTransaction: jest.fn().mockResolvedValue(undefined), abortTransaction: jest.fn().mockResolvedValue(undefined), endSession: jest.fn().mockResolvedValue(undefined), }; const competitionFactModel = deleteManyModel(); const competitionOutboxModel = deleteManyModel(); const reservedCodeId = new mongoose.Types.ObjectId(); const usedCodeId = new mongoose.Types.ObjectId(); const assignmentModel = { ...deleteManyModel(), find: jest.fn().mockReturnValue({ select: jest.fn().mockReturnValue({ session: jest.fn().mockReturnValue({ lean: jest.fn().mockReturnValue( execResult([ { tournamentCodeId: reservedCodeId, state: 'reserved' }, { tournamentCodeId: usedCodeId, state: 'used' }, ]), ), }), }), }), }; const competitionModel = { ...deleteManyModel(), find: jest.fn().mockReturnValue({ select: jest.fn().mockReturnValue({ session: jest.fn().mockReturnValue({ lean: jest .fn() .mockReturnValue(execResult([{ _id: fixture.competition._id }])), }), }), }), }; const matchModel = { find: jest.fn().mockReturnValue({ select: jest .fn() .mockReturnValue(sessionResult([{ _id: fixture.match._id }])), }), deleteMany: jest.fn().mockReturnValue(sessionResult({ deletedCount: 1 })), }; const tournamentCodeModel = { find: jest.fn().mockReturnValue({ select: jest.fn().mockReturnValue({ session: jest.fn().mockReturnValue({ lean: jest.fn().mockReturnValue( execResult([ { _id: reservedCodeId, state: 'reserved', matchId: fixture.match._id, }, { _id: usedCodeId, state: 'used', matchId: fixture.match._id, }, ]), ), }), }), }), updateMany: jest .fn() .mockReturnValue(sessionResult({ matchedCount: 1, modifiedCount: 1 })), }; const matchStatsModel = deleteManyModel(); const quarantineCollection = { deleteMany: jest.fn().mockResolvedValue({ deletedCount: 1 }), }; const connectionService = { createSession: jest.fn().mockResolvedValue(session), getConnection: jest.fn().mockResolvedValue({ collection: jest.fn().mockReturnValue(quarantineCollection), }), getModel: jest.fn((name: string) => { const models: Record = { match: matchModel, competition: competitionModel, competitionFact: competitionFactModel, competitionOutbox: competitionOutboxModel, tournamentCodeAssignment: assignmentModel, tournamentCode: tournamentCodeModel, matchStats: matchStatsModel, }; const model = models[name]; return model ? Promise.resolve(model) : Promise.reject(new Error(`Unexpected model ${name}`)); }), } as unknown as ConnectionService; const communityStatsService = { invalidateCommunity: jest.fn().mockResolvedValue(undefined), } as unknown as jest.Mocked; const service = createService({ connectionService, communityStatsService, }); const result = await service.bulkDeleteLegacyMatches({ communityId: fixture.match.communityId, body: { matchIds: [fixture.match._id.toString()] }, }); expect(result).toEqual({ deleted: 1 }); for (const model of [ competitionFactModel, competitionOutboxModel, assignmentModel, ]) { expect(model.deleteMany).toHaveBeenCalledWith({ competitionId: { $in: [fixture.competition._id] }, }); } expect(competitionModel.deleteMany).toHaveBeenCalledWith({ _id: { $in: [fixture.competition._id] }, }); expect(tournamentCodeModel.updateMany).toHaveBeenCalledTimes(2); expect(matchStatsModel.deleteMany).toHaveBeenCalledWith({ matchId: { $in: [fixture.match._id] }, }); expect(session.commitTransaction).toHaveBeenCalledTimes(1); expect(session.abortTransaction).not.toHaveBeenCalled(); expect(communityStatsService.invalidateCommunity).toHaveBeenCalledWith( fixture.match.communityId, ); }); it('aborts legacy deletion when an active assignment points to another Match code', async () => { const harness = createBulkDeleteFailureHarness({ codeMatchId: new mongoose.Types.ObjectId(), }); await expect( harness.service.bulkDeleteLegacyMatches({ communityId: harness.fixture.match.communityId, body: { matchIds: [harness.fixture.match._id.toString()] }, }), ).rejects.toThrow(/Tournament Code assignment/); expect(harness.session.abortTransaction).toHaveBeenCalledTimes(1); expect(harness.session.commitTransaction).not.toHaveBeenCalled(); expect(harness.matchModel.deleteMany).not.toHaveBeenCalled(); expect(harness.competitionFactModel.deleteMany).not.toHaveBeenCalled(); }); it('aborts legacy deletion when a validated Tournament Code transition does not update exactly once', async () => { const harness = createBulkDeleteFailureHarness({ updateResult: { matchedCount: 0, modifiedCount: 0 }, }); await expect( harness.service.bulkDeleteLegacyMatches({ communityId: harness.fixture.match.communityId, body: { matchIds: [harness.fixture.match._id.toString()] }, }), ).rejects.toThrow(/Tournament Code transition/); expect(harness.session.abortTransaction).toHaveBeenCalledTimes(1); expect(harness.session.commitTransaction).not.toHaveBeenCalled(); expect(harness.matchModel.deleteMany).not.toHaveBeenCalled(); }); it('invalidates community caches again when a committed deletion is retried', async () => { const harness = createBulkDeleteFailureHarness({}); harness.matchModel.find .mockReset() .mockReturnValueOnce({ select: jest .fn() .mockReturnValue(sessionResult([{ _id: harness.fixture.match._id }])), }) .mockReturnValueOnce({ select: jest.fn().mockReturnValue(sessionResult([])), }); harness.communityStatsService.invalidateCommunity .mockRejectedValueOnce(new Error('Redis unavailable')) .mockResolvedValueOnce(0); await expect( harness.service.bulkDeleteLegacyMatches({ communityId: harness.fixture.match.communityId, body: { matchIds: [harness.fixture.match._id.toString()] }, }), ).rejects.toThrow('Redis unavailable'); await expect( harness.service.bulkDeleteLegacyMatches({ communityId: harness.fixture.match.communityId, body: { matchIds: [harness.fixture.match._id.toString()] }, }), ).resolves.toEqual({ deleted: 0 }); expect( harness.communityStatsService.invalidateCommunity, ).toHaveBeenCalledTimes(2); }); it('removes migration quarantine records in the same legacy deletion transaction', async () => { const harness = createBulkDeleteFailureHarness({}); await harness.service.bulkDeleteLegacyMatches({ communityId: harness.fixture.match.communityId, body: { matchIds: [harness.fixture.match._id.toString()] }, }); expect(harness.quarantineCollection.deleteMany).toHaveBeenCalledWith( { _id: { $in: [harness.fixture.match._id] } }, { session: harness.session }, ); }); it('rebuilds a historical legacy Match into Competition facts without rewriting Match.result', async () => { const fixture = createImportFixture(); const historicalMatch = { ...fixture.match, legacyImported: true, result: { riotMatchIds: [fixture.detail.metadata.matchId], games: [ { riotMatchId: fixture.detail.metadata.matchId, participants: [], }, ], seriesResults: [], }, }; const matchModel = { find: jest.fn().mockReturnValue(execResult([historicalMatch])), updateOne: jest.fn().mockReturnValue(execResult({ modifiedCount: 1 })), }; const competitionModel = { find: jest.fn().mockReturnValue({ lean: jest.fn().mockReturnValue(execResult([])), }), }; const riotMatchModel = { find: jest.fn().mockReturnValue({ lean: jest.fn().mockReturnValue( execResult([ { matchId: fixture.detail.metadata.matchId, raw: fixture.detail, }, ]), ), }), }; const connectionService = { getModel: jest.fn(async (name: string) => { if (name === 'match') return matchModel; if (name === 'competition') return competitionModel; if (name === 'riotMatch') return riotMatchModel; throw new Error(`Unexpected model ${name}`); }), } as unknown as ConnectionService; const bootstrapService = { bootstrap: jest.fn().mockResolvedValue(fixture.competition), } as unknown as jest.Mocked; const commandService = { acceptGame: jest.fn().mockResolvedValue({ competition: { ...fixture.competition, revision: 1, phase: 'completed', }, commandId: 'command-1', revision: 1, replayed: false, }), } as unknown as jest.Mocked; const matchStatsService = { buildAndUpsert: jest.fn().mockResolvedValue(undefined), } as unknown as jest.Mocked; const service = createService({ connectionService, matchStatsService, bootstrapService, commandService, }); jest .spyOn( service as unknown as { buildUserByPuuidMap: () => Promise; }, 'buildUserByPuuidMap', ) .mockResolvedValue(fixture.userByPuuid); const result = await service.rebuildLegacyMatches({ communityId: fixture.match.communityId, }); expect(result).toMatchObject({ scanned: 1, rebuilt: 1 }); for (const [, update] of matchModel.updateOne.mock.calls) { expect(update).toEqual( expect.objectContaining({ $set: expect.not.objectContaining({ result: expect.anything() }), }), ); } expect(bootstrapService.bootstrap).toHaveBeenCalledTimes(1); expect(commandService.acceptGame).toHaveBeenCalledWith( expect.objectContaining({ actor: { type: 'system' }, evidence: expect.objectContaining({ type: 'riot', riotMatchId: fixture.detail.metadata.matchId, }), }), ); expect(matchStatsService.buildAndUpsert).toHaveBeenCalledWith( fixture.match._id, { sourceRevision: 1 }, ); }); }); function createService( options: { connectionService?: ConnectionService; communityStatsService?: CommunityStatsService; matchStatsService?: MatchStatsService; bootstrapService?: CompetitionBootstrapService; commandService?: CompetitionCommandService; runWithLock?: ( options: Record, operation: () => Promise, ) => Promise; } = {}, ): LegacyImportService { const distributedLockService = { runWithLock: options.runWithLock ?? (async ( _options: Record, operation: () => Promise, ) => operation()), } as unknown as DistributedLockService; return new ServiceConstructor( options.connectionService ?? ({} as ConnectionService), {} as RedisService, {} as RiotMatchService, options.communityStatsService ?? ({ invalidateCommunity: jest.fn().mockResolvedValue(undefined), } as unknown as CommunityStatsService), options.matchStatsService ?? ({} as MatchStatsService), distributedLockService, options.bootstrapService ?? ({} as CompetitionBootstrapService), options.commandService ?? ({} as CompetitionCommandService), ); } async function importSingleMatch( service: LegacyImportService, riotMatchId: string, job: LegacyImportMemberJob, userByPuuid: UserByPuuidMap, ): Promise { return ( service as unknown as { importSingleMatch: ( riotMatchId: string, job: LegacyImportMemberJob, userByPuuid: UserByPuuidMap, ) => Promise; } ).importSingleMatch(riotMatchId, job, userByPuuid); } function createImportFixture() { const communityId = new mongoose.Types.ObjectId(); const triggeredBy = new mongoose.Types.ObjectId(); const matchId = new mongoose.Types.ObjectId(); const competitionId = new mongoose.Types.ObjectId(); const seriesId = new mongoose.Types.ObjectId(); const gameSlotId = new mongoose.Types.ObjectId(); const blueTeamId = new mongoose.Types.ObjectId(); const redTeamId = new mongoose.Types.ObjectId(); const users = Array.from({ length: 10 }, (_, index) => ({ userId: new mongoose.Types.ObjectId(), puuid: `puuid-${index + 1}`, })); const userByPuuid: UserByPuuidMap = new Map( users.map(({ userId, puuid }, index) => [ puuid, { userId, account: { puuid, gameName: `player-${index + 1}`, tagLine: 'KR1', profileIconId: index + 1, tiers: [], isPrimary: true, }, displayName: `player-${index + 1}`, preferredPositions: [], } as LegacyUserSnapshot, ]), ); const participants = users.map(({ puuid }, index) => ({ puuid, participantId: index + 1, teamId: index < 5 ? 100 : 200, championId: index + 1, teamPosition: ['TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM', 'UTILITY'][index % 5], kills: index < 5 ? 10 : 2, deaths: index < 5 ? 2 : 10, assists: index < 5 ? 8 : 3, win: index < 5, })); const detail = { metadata: { dataVersion: '2', matchId: 'KR_legacy_1', participants: users.map(({ puuid }) => puuid), }, info: { gameCreation: Date.parse('2026-07-12T10:00:00.000Z'), gameEndTimestamp: Date.parse('2026-07-12T10:30:00.000Z'), gameDuration: 1_800, mapId: 11, tournamentCode: 'LEGACY-CODE', participants, teams: [ { teamId: 100, win: true }, { teamId: 200, win: false }, ], }, } as unknown as RiotMatchDto; const match = { _id: matchId, communityId, title: 'legacy', description: 'Legacy import (자동 생성)', mapId: 11, status: 'team-built', scheduledAt: new Date(detail.info.gameCreation), maxParticipants: 10, gameCount: 1, gameMode: 'pair', tournamentCodeIds: [], gameSchedule: [], teamBuiltAt: new Date(detail.info.gameCreation), hostUserId: triggeredBy, participants: users.map(({ userId, puuid }, index) => ({ userId, puuid, gameName: `player-${index + 1}`, tagLine: 'KR1', profileIconId: index + 1, preferredPositions: [], joinedAt: new Date(detail.info.gameCreation), })), teams: [ { teamIndex: 1, name: '1팀', members: users.slice(0, 5).map(({ userId }, index) => ({ userId, assignedPosition: ['TOP', 'JGL', 'MID', 'ADC', 'SUP'][index], })), }, { teamIndex: 2, name: '2팀', members: users.slice(5).map(({ userId }, index) => ({ userId, assignedPosition: ['TOP', 'JGL', 'MID', 'ADC', 'SUP'][index], })), }, ], prizes: [], notices: [], schedule: [], }; const competition = { _id: competitionId, matchId, communityId, revision: 0, phase: 'ready', teams: [ { teamId: blueTeamId, legacyTeamIndex: 1, displayOrder: 1, seedNumber: 1, name: '1팀', members: users.slice(0, 5).map(({ userId }) => ({ userId })), }, { teamId: redTeamId, legacyTeamIndex: 2, displayOrder: 2, seedNumber: 2, name: '2팀', members: users.slice(5).map(({ userId }) => ({ userId })), }, ], projection: { phase: 'ready', series: [ { seriesId, status: 'ready', entries: [ { slot: 'A', teamId: blueTeamId, gameWins: 0 }, { slot: 'B', teamId: redTeamId, gameWins: 0 }, ], }, ], gameSlots: [ { id: gameSlotId, seriesId, ordinal: 1, displayNumber: 1, status: 'ready', }, ], games: [], }, }; const job: LegacyImportMemberJob = { kind: 'legacy-import-member', jobId: 'member-job-1', parentJobId: 'legacy-job-1', communityId: communityId.toString(), userId: users[0].userId.toString(), puuid: users[0].puuid, startTime: 1, endTime: 2, triggeredBy: triggeredBy.toString(), region: 'asia', }; return { detail, match, competition, blueTeamId, redTeamId, job, userByPuuid, }; } function execResult(value: T) { return { exec: jest.fn().mockResolvedValue(value) }; } function sessionResult(value: T) { const query = { exec: jest.fn().mockResolvedValue(value), session: jest.fn(), }; query.session.mockReturnValue(query); return query; } function deleteManyModel() { return { deleteMany: jest .fn() .mockReturnValue(sessionResult({ acknowledged: true, deletedCount: 1 })), }; } function createBulkDeleteFailureHarness(options: { codeMatchId?: mongoose.Types.ObjectId; codeState?: 'reserved' | 'used'; assignmentState?: 'reserved' | 'used'; updateResult?: { matchedCount: number; modifiedCount: number }; }) { const fixture = createImportFixture(); const session = { startTransaction: jest.fn(), commitTransaction: jest.fn().mockResolvedValue(undefined), abortTransaction: jest.fn().mockResolvedValue(undefined), endSession: jest.fn().mockResolvedValue(undefined), }; const tournamentCodeId = new mongoose.Types.ObjectId(); const assignmentState = options.assignmentState ?? 'reserved'; const codeState = options.codeState ?? assignmentState; const assignmentModel = { ...deleteManyModel(), find: jest.fn().mockReturnValue({ select: jest.fn().mockReturnValue({ session: jest.fn().mockReturnValue({ lean: jest .fn() .mockReturnValue( execResult([{ tournamentCodeId, state: assignmentState }]), ), }), }), }), }; const competitionModel = { ...deleteManyModel(), find: jest.fn().mockReturnValue({ select: jest.fn().mockReturnValue({ session: jest.fn().mockReturnValue({ lean: jest .fn() .mockReturnValue(execResult([{ _id: fixture.competition._id }])), }), }), }), }; const matchModel = { find: jest.fn().mockReturnValue({ select: jest .fn() .mockReturnValue(sessionResult([{ _id: fixture.match._id }])), }), deleteMany: jest.fn().mockReturnValue(sessionResult({ deletedCount: 1 })), }; const tournamentCodeModel = { find: jest.fn().mockReturnValue({ select: jest.fn().mockReturnValue({ session: jest.fn().mockReturnValue({ lean: jest.fn().mockReturnValue( execResult([ { _id: tournamentCodeId, state: codeState, matchId: options.codeMatchId ?? fixture.match._id, }, ]), ), }), }), }), updateMany: jest .fn() .mockReturnValue( sessionResult( options.updateResult ?? { matchedCount: 1, modifiedCount: 1 }, ), ), }; const competitionFactModel = deleteManyModel(); const competitionOutboxModel = deleteManyModel(); const matchStatsModel = deleteManyModel(); const quarantineCollection = { deleteMany: jest.fn().mockResolvedValue({ deletedCount: 1 }), }; const connectionService = { createSession: jest.fn().mockResolvedValue(session), getConnection: jest.fn().mockResolvedValue({ collection: jest.fn().mockReturnValue(quarantineCollection), }), getModel: jest.fn((name: string) => { const models: Record = { match: matchModel, competition: competitionModel, competitionFact: competitionFactModel, competitionOutbox: competitionOutboxModel, tournamentCodeAssignment: assignmentModel, tournamentCode: tournamentCodeModel, matchStats: matchStatsModel, }; const model = models[name]; return model ? Promise.resolve(model) : Promise.reject(new Error(`Unexpected model ${name}`)); }), } as unknown as ConnectionService; const communityStatsService = { invalidateCommunity: jest.fn().mockResolvedValue(0), } as unknown as jest.Mocked; const service = createService({ connectionService, communityStatsService }); return { fixture, session, service, matchModel, competitionFactModel, communityStatsService, quarantineCollection, }; }