import { Injectable, Logger } from '@nestjs/common'; import mongoose from 'mongoose'; import { ConnectionService } from '../global/database/connection.service'; import { ChampionMasteryEntry, MatchStatus, RiotAccount, TierInfo, } from '../global/database/schema'; import { RiotAccountService } from './riot-account.service'; import { RiotChampionMasteryService } from './riot-champion-mastery.service'; import { RiotApiError } from './riot.client.service'; import { RiotLeagueService } from './riot-league.service'; import { RIOT_RECENT_MATCH_LIMIT, RiotRecentMatchesService, } from './riot-recent-matches.service'; import { RiotRecentStatsService } from './riot-recent-stats.service'; import { RiotSummonerService } from './riot-summoner.service'; import { RiotChampionMasteryDto, RiotLeagueEntryDto, RiotMatchDto, RiotPlatformRoute, RiotRegionalRoute, RiotSummonerDto, } from './riot.types'; const DEFAULT_PLATFORM: RiotPlatformRoute = 'kr'; const DEFAULT_REGION: RiotRegionalRoute = 'asia'; const MASTERY_LIMIT = 10; const DEFAULT_SUMMONER_TTL_MS = 24 * 60 * 60 * 1000; // 24h const DEFAULT_LEAGUE_TTL_MS = 60 * 60 * 1000; // 1h const DEFAULT_MASTERY_TTL_MS = 6 * 60 * 60 * 1000; // 6h const DEFAULT_RECENT_MATCHES_TTL_MS = 6 * 60 * 60 * 1000; // 6h const ACTIVE_MATCH_STATUSES: MatchStatus[] = [ 'recruiting', 'team-built', 'in-progress', ]; export interface EnrichOptions { platform?: RiotPlatformRoute; region?: RiotRegionalRoute; force?: boolean; summonerTtlMs?: number; leagueTtlMs?: number; masteryTtlMs?: number; recentMatchesTtlMs?: number; } export interface EnrichResult { summoner: 'updated' | 'fresh' | 'failed'; league: 'updated' | 'fresh' | 'failed'; masteries: 'updated' | 'fresh' | 'failed'; recentMatches: 'updated' | 'fresh' | 'failed'; account: RiotAccount | null; } export type RefreshLeagueEntriesResult = 'updated' | 'failed'; @Injectable() export class RiotAccountEnrichmentService { private readonly logger = new Logger(RiotAccountEnrichmentService.name); private readonly inFlight = new Map>(); constructor( private readonly connectionService: ConnectionService, private readonly accountService: RiotAccountService, private readonly summonerService: RiotSummonerService, private readonly leagueService: RiotLeagueService, private readonly masteryService: RiotChampionMasteryService, private readonly recentMatchesService: RiotRecentMatchesService, private readonly recentStatsService: RiotRecentStatsService, ) {} public async markRefreshRequested( userId: mongoose.Types.ObjectId, puuid: string, at: Date = new Date(), ): Promise { const UserModel = await this.connectionService.getModel('user'); await UserModel.updateOne( { _id: userId, 'riotAccounts.puuid': puuid }, { $set: { 'riotAccounts.$.lastRefreshRequestedAt': at } }, ).exec(); } public async enrichRiotAccount(params: { userId: mongoose.Types.ObjectId; puuid: string; options?: EnrichOptions; }): Promise { const key = `${params.userId.toString()}:${params.puuid}`; const existing = this.inFlight.get(key); if (existing) return existing; const promise = this.doEnrichRiotAccount(params).finally(() => { this.inFlight.delete(key); }); this.inFlight.set(key, promise); return promise; } public async refreshLeagueEntries(params: { userId: mongoose.Types.ObjectId; puuid: string; platform?: RiotPlatformRoute; }): Promise { const UserModel = await this.connectionService.getModel('user'); const user = await UserModel.findById(params.userId).exec(); if (!user) return 'failed'; const account = user.riotAccounts.find((a) => a.puuid === params.puuid); if (!account) return 'failed'; const outcome = await this.fetchLeagueSafe( params.puuid, params.platform ?? DEFAULT_PLATFORM, ); if (outcome.status !== 'updated' || !outcome.dto) return 'failed'; this.applyLeagueEntries(account, outcome.dto); await user.save(); await this.syncActiveMatchParticipantTier( user._id, params.puuid, account.tiers, ); return 'updated'; } private async doEnrichRiotAccount(params: { userId: mongoose.Types.ObjectId; puuid: string; options?: EnrichOptions; }): Promise { const UserModel = await this.connectionService.getModel('user'); const user = await UserModel.findById(params.userId).exec(); if (!user) { return { summoner: 'failed', league: 'failed', masteries: 'failed', recentMatches: 'failed', account: null, }; } const account = user.riotAccounts.find((a) => a.puuid === params.puuid); if (!account) { return { summoner: 'failed', league: 'failed', masteries: 'failed', recentMatches: 'failed', account: null, }; } const CommunityModel = await this.connectionService.getModel('community'); const community = await CommunityModel.findById(user.communityId) .select({ riotPlatform: 1, riotRegion: 1, seasonStartedAt: 1 }) .lean() .exec(); const opts = params.options ?? {}; const platform = opts.platform ?? community?.riotPlatform ?? DEFAULT_PLATFORM; const region = opts.region ?? community?.riotRegion ?? DEFAULT_REGION; const now = Date.now(); const summonerTtl = opts.summonerTtlMs ?? DEFAULT_SUMMONER_TTL_MS; const leagueTtl = opts.leagueTtlMs ?? DEFAULT_LEAGUE_TTL_MS; const masteryTtl = opts.masteryTtlMs ?? DEFAULT_MASTERY_TTL_MS; const recentMatchesTtl = opts.recentMatchesTtlMs ?? DEFAULT_RECENT_MATCHES_TTL_MS; const force = opts.force === true; const seasonStartedAt = community?.seasonStartedAt ? new Date(community.seasonStartedAt) : undefined; const seasonInvalidatesRecentStats = seasonStartedAt !== undefined && (!account.recentStatsFetchedAt || account.recentStatsFetchedAt.getTime() < seasonStartedAt.getTime()); const summonerStale = force || account.revisionDate === 0 || now - account.revisionDate > summonerTtl; const leagueStale = force || account.tiers.length === 0 || this.tiersOldestAt(account.tiers) < now - leagueTtl; const masteryStale = force || !account.championMasteriesFetchedAt || now - account.championMasteriesFetchedAt.getTime() > masteryTtl; const recentMatchesStale = force || seasonInvalidatesRecentStats || !account.recentStatsFetchedAt || !account.recentStatsSummary || now - account.recentStatsFetchedAt.getTime() > recentMatchesTtl; const summonerOutcome = summonerStale ? await this.fetchSummonerSafe(params.puuid, platform, region) : { status: 'fresh' as const, dto: null, platform }; const effectivePlatform = summonerOutcome.platform ?? platform; const [leagueOutcome, masteryOutcome, recentMatchesOutcome] = await Promise.all([ leagueStale ? this.fetchLeagueSafe(params.puuid, effectivePlatform) : Promise.resolve({ status: 'fresh' as const, dto: null }), masteryStale ? this.fetchMasteriesSafe(params.puuid, effectivePlatform) : Promise.resolve({ status: 'fresh' as const, dto: null }), recentMatchesStale ? this.fetchRecentMatchesSafe(params.puuid, region, seasonStartedAt) : Promise.resolve({ status: 'fresh' as const, summary: null, matchIds: null, }), ]); if (summonerOutcome.status === 'updated' && summonerOutcome.dto) { this.applySummoner(account, summonerOutcome.dto); } if (leagueOutcome.status === 'updated' && leagueOutcome.dto) { this.applyLeagueEntries(account, leagueOutcome.dto); } if (masteryOutcome.status === 'updated' && masteryOutcome.dto) { this.applyMasteries(account, masteryOutcome.dto); } if ( recentMatchesOutcome.status === 'updated' && recentMatchesOutcome.summary && recentMatchesOutcome.matchIds ) { this.applyRecentMatches( account, recentMatchesOutcome.summary, recentMatchesOutcome.matchIds, ); } if ( summonerOutcome.status === 'updated' || leagueOutcome.status === 'updated' || masteryOutcome.status === 'updated' || recentMatchesOutcome.status === 'updated' ) { await user.save(); } if (leagueOutcome.status === 'updated') { await this.syncActiveMatchParticipantTier( user._id, params.puuid, account.tiers, ); } return { summoner: summonerOutcome.status, league: leagueOutcome.status, masteries: masteryOutcome.status, recentMatches: recentMatchesOutcome.status, account, }; } private async fetchSummonerSafe( puuid: string, platform: RiotPlatformRoute, region: RiotRegionalRoute, ): Promise< | { status: 'updated'; dto: RiotSummonerDto; platform: RiotPlatformRoute } | { status: 'failed'; dto: null; platform: RiotPlatformRoute } > { try { const dto = await this.summonerService.getByPuuid(puuid, { platform }); return { status: 'updated', dto, platform }; } catch (err) { if (err instanceof RiotApiError && err.status === 404) { try { const regionDto = await this.accountService.getRegionByPuuid(puuid, { region, }); if (regionDto.region !== platform) { this.logger.warn( `Summoner platform corrected for ${puuid}: ${platform} -> ${regionDto.region}`, ); } const dto = await this.summonerService.getByPuuid(puuid, { platform: regionDto.region, }); return { status: 'updated', dto, platform: regionDto.region }; } catch (fallbackErr) { this.logger.warn( `Summoner fallback fetch failed for ${puuid}: ${ (fallbackErr as Error)?.message ?? fallbackErr }`, ); return { status: 'failed', dto: null, platform }; } } this.logger.warn( `Summoner fetch failed for ${puuid}: ${(err as Error)?.message ?? err}`, ); return { status: 'failed', dto: null, platform }; } } private async fetchLeagueSafe( puuid: string, platform: RiotPlatformRoute, ): Promise< | { status: 'updated'; dto: RiotLeagueEntryDto[] } | { status: 'failed'; dto: null } > { try { const dto = await this.leagueService.getEntriesByPuuid(puuid, { platform, }); return { status: 'updated', dto }; } catch (err) { this.logger.warn( `League entries fetch failed for ${puuid}: ${ (err as Error)?.message ?? err }`, ); return { status: 'failed', dto: null }; } } private async fetchMasteriesSafe( puuid: string, platform: RiotPlatformRoute, ): Promise< | { status: 'updated'; dto: RiotChampionMasteryDto[] } | { status: 'failed'; dto: null } > { try { const dto = await this.masteryService.getTopByPuuid(puuid, { platform, count: MASTERY_LIMIT, }); return { status: 'updated', dto }; } catch (err) { this.logger.warn( `Champion masteries fetch failed for ${puuid}: ${ (err as Error)?.message ?? err }`, ); return { status: 'failed', dto: null }; } } private async fetchRecentMatchesSafe( puuid: string, region: RiotRegionalRoute, seasonStartedAt?: Date, ): Promise< | { status: 'updated'; summary: RiotAccount['recentStatsSummary']; matchIds: string[]; } | { status: 'failed'; summary: null; matchIds: null } > { try { await this.recentMatchesService.syncRecentMatches({ puuid, region, limit: RIOT_RECENT_MATCH_LIMIT, }); const matches = await this.recentMatchesService.loadFromDb({ puuid, limit: RIOT_RECENT_MATCH_LIMIT, }); const summary = this.recentStatsService.computeSummary( matches.map((match) => match.raw as unknown as RiotMatchDto), puuid, { seasonStartedAt }, ); return { status: 'updated', summary, matchIds: matches.map((match) => match.matchId), }; } catch (err) { this.logger.warn( `Recent matches fetch failed for ${puuid}: ${ (err as Error)?.message ?? err }`, ); return { status: 'failed', summary: null, matchIds: null }; } } private applySummoner(account: RiotAccount, dto: RiotSummonerDto): void { account.profileIconId = dto.profileIconId; account.revisionDate = dto.revisionDate; account.summonerLevel = dto.summonerLevel; } private applyLeagueEntries( account: RiotAccount, entries: RiotLeagueEntryDto[], ): void { const fetchedAt = new Date(); this.appendTierHistoryIfChanged(account, entries, fetchedAt); const next: TierInfo[] = entries.map((e) => ({ leagueId: e.leagueId, queueType: e.queueType, tier: e.tier, rank: e.rank, puuid: e.puuid, leaguePoints: e.leaguePoints, wins: e.wins, losses: e.losses, veteran: e.veteran, inactive: e.inactive, freshBlood: e.freshBlood, hotStreak: e.hotStreak, miniSeries: e.miniSeries, fetchedAt, })); account.tiers = next; } private appendTierHistoryIfChanged( account: RiotAccount, entries: RiotLeagueEntryDto[], recordedAt: Date, ): void { for (const entry of entries) { const last = [...account.tierHistory] .reverse() .find((history) => history.queueType === entry.queueType); const changed = !last || last.tier !== entry.tier || (last.rank ?? '') !== (entry.rank ?? '') || last.leaguePoints !== entry.leaguePoints || last.wins !== entry.wins || last.losses !== entry.losses; if (!changed) continue; account.tierHistory.push({ queueType: entry.queueType, tier: entry.tier, rank: entry.rank, leaguePoints: entry.leaguePoints, wins: entry.wins, losses: entry.losses, recordedAt, }); } } private applyMasteries( account: RiotAccount, masteries: RiotChampionMasteryDto[], ): void { const summary: ChampionMasteryEntry[] = masteries .slice(0, MASTERY_LIMIT) .map((m) => ({ ...m })); account.championMasteries = summary; account.championMasteriesFetchedAt = new Date(); } private applyRecentMatches( account: RiotAccount, summary: NonNullable, matchIds: string[], ): void { const fetchedAt = new Date(); account.recentStatsSummary = summary; account.recentStatsFetchedAt = fetchedAt; account.matchIds = matchIds; account.matchIdsFetchedAt = fetchedAt; } private async syncActiveMatchParticipantTier( userId: mongoose.Types.ObjectId, puuid: string, tiers: TierInfo[], ): Promise { const MatchModel = await this.connectionService.getModel('match'); const tier = this.selectParticipantTier(tiers); const update = tier ? { $set: { 'participants.$[participant].tier': tier } } : { $unset: { 'participants.$[participant].tier': '' } }; await MatchModel.updateMany( { status: { $in: ACTIVE_MATCH_STATUSES }, participants: { $elemMatch: { userId, puuid, }, }, }, update, { arrayFilters: [ { 'participant.userId': userId, 'participant.puuid': puuid, }, ], }, ).exec(); } private selectParticipantTier(tiers: TierInfo[]): TierInfo | undefined { const tier = tiers.find((entry) => entry.queueType === 'RANKED_SOLO_5x5') ?? tiers[0]; if (!tier) return undefined; return { leagueId: tier.leagueId, queueType: tier.queueType, tier: tier.tier, rank: tier.rank, puuid: tier.puuid, leaguePoints: tier.leaguePoints, wins: tier.wins, losses: tier.losses, veteran: tier.veteran, inactive: tier.inactive, freshBlood: tier.freshBlood, hotStreak: tier.hotStreak, miniSeries: tier.miniSeries, fetchedAt: tier.fetchedAt, }; } private tiersOldestAt(tiers: TierInfo[]): number { if (tiers.length === 0) return 0; let oldest = Infinity; for (const t of tiers) { const at = t.fetchedAt instanceof Date ? t.fetchedAt.getTime() : 0; if (at < oldest) oldest = at; } return oldest === Infinity ? 0 : oldest; } }