import { Injectable, Logger } from '@nestjs/common'; import mongoose from 'mongoose'; import { ConnectionService } from '../global/database/connection.service'; import type { MatchDocument } from '../global/database/schema'; import { RiotMatchService } from '../riot/riot-match.service'; import { RIOT_REGIONAL_ROUTES, type RiotMatchDto, type RiotMatchTimelineDto, type RiotRegionalRoute, } from '../riot/riot.types'; import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder'; import { MatchStatsRepository } from './match-stats.repository'; import { MATCH_STATS_BUILDER_VERSION } from './match-stats.types'; @Injectable() export class MatchStatsService { private readonly logger = new Logger(MatchStatsService.name); constructor( private readonly connectionService: ConnectionService, private readonly repository: MatchStatsRepository, private readonly builder: MatchStatsFragmentBuilder, private readonly riotMatchService: RiotMatchService, ) {} public async buildAndUpsert( matchId: mongoose.Types.ObjectId, options: { includeTimeline?: boolean } = {}, ): Promise { const MatchModel = await this.connectionService.getModel('match'); const RiotMatchModel = await this.connectionService.getModel('riotMatch'); const match = await MatchModel.findById(matchId).exec(); if (!match) return; if (!this.isEligible(match)) { await this.repository.deleteByMatch(matchId); return; } const riotIds = [ ...new Set( (match.result?.games ?? []) .map((game) => game.riotMatchId) .filter((riotMatchId): riotMatchId is string => Boolean(riotMatchId)), ), ]; const riotDocs = riotIds.length > 0 ? await RiotMatchModel.find({ matchId: { $in: riotIds } }) .lean() .exec() : []; const rawByRiotMatchId = new Map( riotDocs.map((doc) => [doc.matchId, doc.raw as unknown as RiotMatchDto]), ); const timelineByRiotMatchId = new Map(); for (const doc of riotDocs) { if (isRiotMatchTimelineDto(doc.timeline)) { timelineByRiotMatchId.set(doc.matchId, doc.timeline); } } if ( options.includeTimeline && riotDocs.length > 0 && timelineByRiotMatchId.size < riotDocs.length ) { const region = await this.resolveRiotRegion(match.communityId); for (const doc of riotDocs) { if (timelineByRiotMatchId.has(doc.matchId)) continue; try { const timeline = await this.riotMatchService.getMatchTimeline( doc.matchId, { region }, ); await RiotMatchModel.updateOne( { matchId: doc.matchId }, { $set: { timeline: timeline as unknown as Record, timelineFetchedAt: new Date(), }, }, ).exec(); timelineByRiotMatchId.set(doc.matchId, timeline); } catch (error) { this.logger.warn( `Failed to fetch match timeline for ${doc.matchId}: ${ error instanceof Error ? error.message : error }`, ); } } } const fragment = this.builder.buildFragment({ match, rawByRiotMatchId, timelineByRiotMatchId, timelineLoadAttempted: options.includeTimeline === true, }); await this.repository.upsert({ matchId: match._id, communityId: match.communityId, scheduledAt: match.scheduledAt, gameCreationMin: fragment.gameCreationMin, gameCreationMax: fragment.gameCreationMax, userIds: fragment.userIds, championIds: fragment.championIds, matchCard: fragment.matchCard as unknown as Record, records: fragment.records, gameDetails: fragment.gameDetails, builtAt: new Date(), builderVersion: MATCH_STATS_BUILDER_VERSION, }); } public async removeByMatch(matchId: mongoose.Types.ObjectId): Promise { await this.repository.deleteByMatch(matchId); } public async removeByMatches( matchIds: mongoose.Types.ObjectId[], ): Promise { await this.repository.deleteByMatches(matchIds); } public async backfillCommunity( communityId: mongoose.Types.ObjectId, ): Promise<{ processed: number; failed: number }> { const MatchModel = await this.connectionService.getModel('match'); const matches = await MatchModel.find({ communityId, status: { $in: ['finished', 'in-progress'] }, 'result.games.0': { $exists: true }, }) .sort({ scheduledAt: -1 }) .select({ _id: 1 }) .exec(); let processed = 0; let failed = 0; for (const match of matches) { try { await this.buildAndUpsert(match._id); processed += 1; } catch { failed += 1; } } return { processed, failed }; } private isEligible(match: MatchDocument): boolean { return ( (match.status === 'finished' || match.status === 'in-progress') && Boolean(match.result?.games?.length) ); } private async resolveRiotRegion( communityId: mongoose.Types.ObjectId, ): Promise { const CommunityModel = await this.connectionService.getModel('community'); const community = await CommunityModel.findById(communityId) .select({ riotRegion: 1 }) .lean() .exec(); const region = community?.riotRegion; return RIOT_REGIONAL_ROUTES.includes(region as RiotRegionalRoute) ? (region as RiotRegionalRoute) : 'asia'; } } function isRiotMatchTimelineDto( value: unknown, ): value is RiotMatchTimelineDto { if (!isRecord(value) || !isRecord(value.info)) return false; return Array.isArray(value.info.frames); } function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null; }