import { BadRequestException, Injectable, InternalServerErrorException, Logger, NotFoundException, } from '@nestjs/common'; import { randomUUID } from 'crypto'; import mongoose from 'mongoose'; import { ConnectionService } from '../global/database/connection.service'; import { AuctionActionType, AuctionChatMessage, AuctionDocument, AuctionPlayerSnapshot, AuctionTeam, AuctionTopTierThreshold, MatchParticipant, MatchTeamMember, Position, RiotAccount, } from '../global/database/schema'; import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service'; import type { RiotPlatformRoute, RiotRegionalRoute } from '../riot/riot.types'; import { TournamentCodeService } from '../tournament-code/tournament-code.service'; import { TournamentResultService } from '../tournament-result/tournament-result.service'; const AUCTION_MAX_TEAM_SIZE = 5; const AUCTION_BACKGROUND_ENRICHMENT_CONCURRENCY = 1; const AUCTION_ENRICHMENT_COOLDOWN_MS = 3 * 60 * 60 * 1000; const AUCTION_CHAT_MAX_MESSAGES = 200; const AUCTION_CHAT_MAX_MESSAGE_LENGTH = 300; const AUCTION_CHAT_MAX_DISPLAY_NAME_LENGTH = 24; interface StartAuctionParams { matchId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId; captains: { teamIndex: number; userId: mongoose.Types.ObjectId; initialPoints?: number; }[]; initialPoints: number; maxTimerSeconds: number; bidExtensionSeconds: number; topTierThreshold: AuctionTopTierThreshold; manualTopTierUserIds: mongoose.Types.ObjectId[]; } interface PlaceBidParams { matchId: mongoose.Types.ObjectId; teamIndex: number; amount: number; bidderUserId?: mongoose.Types.ObjectId; } interface MarkSoldParams { matchId: mongoose.Types.ObjectId; assignedPosition?: Position; } interface AppendChatMessageParams { matchId: mongoose.Types.ObjectId; userId?: mongoose.Types.ObjectId; displayName?: string; message: string; } export interface AuctionHistoryView { sequence: number; action: AuctionActionType; actionLabel: string; takenAt: Date; } interface AuctionEnrichmentTarget { userId: mongoose.Types.ObjectId; puuid: string; } @Injectable() export class AuctionService { private readonly logger = new Logger(AuctionService.name); constructor( private readonly connectionService: ConnectionService, private readonly enrichmentService: RiotAccountEnrichmentService, private readonly tournamentCodeService: TournamentCodeService, private readonly tournamentResultService: TournamentResultService, ) {} public async start(params: StartAuctionParams): Promise { const MatchModel = await this.connectionService.getModel('match'); const UserModel = await this.connectionService.getModel('user'); const AuctionModel = await this.connectionService.getModel('auction'); const CommunityModel = await this.connectionService.getModel('community'); const match = await MatchModel.findById(params.matchId); if (!match) throw new NotFoundException('Match not found.'); if (!match.communityId.equals(params.communityId)) { throw new BadRequestException('Match does not belong to this community.'); } const existing = await AuctionModel.findOne({ matchId: params.matchId }); if (existing) { throw new BadRequestException('Auction already exists for this match.'); } const activeParticipants = this.applyAuctionCut(match); const desiredAuctionCount = activeParticipants.length; if (desiredAuctionCount < 10) { throw new BadRequestException('Not enough participants (need at least 10).'); } const expectedCaptainCount = desiredAuctionCount / AUCTION_MAX_TEAM_SIZE; if (params.captains.length !== expectedCaptainCount) { throw new BadRequestException( `Expected ${expectedCaptainCount} captains for ${desiredAuctionCount} participants.`, ); } this.assertCaptainAssignments( params.captains, activeParticipants, expectedCaptainCount, ); const captainUserIds = params.captains.map((c) => c.userId); const basePlayerUsers = await UserModel.find({ _id: { $in: activeParticipants .filter((p) => !captainUserIds.some((cid) => cid.equals(p.userId))) .map((p) => p.userId), }, }); const community = await CommunityModel.findById(match.communityId) .select({ riotPlatform: 1, riotRegion: 1 }) .lean() .exec(); const platform = community?.riotPlatform ?? 'kr'; const region = community?.riotRegion ?? 'asia'; const enrichCooldownCutoff = Date.now() - AUCTION_ENRICHMENT_COOLDOWN_MS; const enrichTargets = basePlayerUsers.flatMap((user) => { const account = user.riotAccounts.find((entry) => entry.isPrimary) ?? user.riotAccounts[0]; if (!account?.puuid) return []; if (this.wasRecentlyRefreshed(account, enrichCooldownCutoff)) return []; return [{ userId: user._id, puuid: account.puuid }]; }); const userById = new Map(basePlayerUsers.map((u) => [u._id.toString(), u])); const nonCaptainPuuids = new Set(); const order: AuctionPlayerSnapshot[] = []; for (const participant of activeParticipants) { if (captainUserIds.some((cid) => cid.equals(participant.userId))) { continue; } const user = userById.get(participant.userId.toString()); if (!user) continue; const primary = user.riotAccounts.find((a) => a.isPrimary) ?? user.riotAccounts[0]; if (!primary) { throw new BadRequestException( `Participant ${user._id.toString()} has no Riot account.`, ); } if (nonCaptainPuuids.has(primary.puuid)) continue; nonCaptainPuuids.add(primary.puuid); order.push({ userId: user._id, puuid: primary.puuid, gameName: primary.gameName, tagLine: primary.tagLine, profileIconId: primary.profileIconId, preferredPositions: participant.preferredPositions, tiers: primary.tiers, masteries: primary.championMasteries, recentStatsSummary: primary.recentStatsSummary, passCount: 0, }); } const shuffledOrder = this.shuffleAuctionPlayerOrder(order); const prioritizedOrder = this.applyTopTierPriority( shuffledOrder, params.topTierThreshold, params.manualTopTierUserIds, ); const auction = await AuctionModel.create({ matchId: params.matchId, phase: 'presenting', teams: params.captains.map((c) => ({ teamIndex: c.teamIndex, captainUserId: c.userId, points: c.initialPoints ?? params.initialPoints, members: [], })), order: prioritizedOrder, passedQueue: [], auctionRound: 1, currentIndex: 0, bids: [], currentBid: 0, maxTimerSeconds: params.maxTimerSeconds, bidExtensionSeconds: params.bidExtensionSeconds, initialPoints: params.initialPoints, topTierThreshold: params.topTierThreshold, manualTopTierUserIds: params.topTierThreshold === 'MANUAL' ? params.manualTopTierUserIds : [], startedAt: new Date(), }); await this.recordSnapshot(auction, 'start'); match.status = 'team-built'; match.teamBuiltAt = match.teamBuiltAt ?? new Date(); await match.save(); this.enqueueBackgroundOrderEnrichment({ auctionId: auction._id, targets: enrichTargets, platform, region, }); return auction; } public async getByMatchId( matchId: mongoose.Types.ObjectId, ): Promise { const AuctionModel = await this.connectionService.getModel('auction'); const auction = await AuctionModel.findOne({ matchId }); if (!auction) throw new NotFoundException('Auction not found.'); return auction; } public async appendChatMessage(params: AppendChatMessageParams): Promise<{ auction: AuctionDocument; message: AuctionChatMessage; }> { const auction = await this.getByMatchId(params.matchId); const messageText = this.normalizeChatMessage(params.message); const message: AuctionChatMessage = { id: randomUUID(), userId: params.userId, displayName: this.normalizeChatDisplayName(params.displayName), message: messageText, sentAt: new Date(), }; auction.chatMessages ??= []; auction.chatMessages.push(message); const overflow = auction.chatMessages.length - AUCTION_CHAT_MAX_MESSAGES; if (overflow > 0) { auction.chatMessages.splice(0, overflow); } await auction.save(); return { auction, message }; } public async listHistory(params: { matchId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId; }): Promise { const MatchModel = await this.connectionService.getModel('match'); const AuctionHistoryModel = await this.connectionService.getModel('auctionHistory'); const match = await MatchModel.findById(params.matchId).select({ communityId: 1, }); if (!match) throw new NotFoundException('Match not found.'); if (!match.communityId.equals(params.communityId)) { throw new BadRequestException('Match does not belong to this community.'); } const entries = await AuctionHistoryModel.find({ matchId: params.matchId }) .sort({ sequence: -1 }) .limit(100) .lean() .exec(); return entries.map((entry) => ({ sequence: entry.sequence, action: entry.action, actionLabel: this.formatHistoryActionLabel(entry.action), takenAt: entry.takenAt, })); } public async openBidding( matchId: mongoose.Types.ObjectId, ): Promise { const auction = await this.getByMatchId(matchId); if (auction.phase !== 'presenting') { throw new BadRequestException('Auction is not in presenting phase.'); } await this.recordSnapshot(auction, 'open-bidding'); auction.phase = 'bidding'; auction.currentBid = 0; auction.currentBidderTeamIndex = undefined; auction.currentDeadline = this.createDeadline(auction.maxTimerSeconds); await auction.save(); return auction; } public async placeBid(params: PlaceBidParams): Promise { const auction = await this.getByMatchId(params.matchId); if (auction.phase !== 'bidding') { throw new BadRequestException('Auction is not in bidding phase.'); } const team = this.findAuctionTeamByIndex(auction, params.teamIndex); if (!team) throw new BadRequestException('Unknown team.'); if (params.amount <= auction.currentBid) { throw new BadRequestException('Bid must exceed current bid.'); } if (params.amount > team.points) { throw new BadRequestException('Bid exceeds team points.'); } this.assertTeamHasSlot(team); // 임시 운영용: 클라이언트에서 선택한 팀장 모드를 신뢰하고 실제 로그인 사용자 검증은 건너뛴다. await this.recordSnapshot(auction, 'bid', params.bidderUserId); auction.currentBid = params.amount; auction.currentBidderTeamIndex = params.teamIndex; auction.currentDeadline = this.createDeadline( this.resolveBidExtensionSeconds(auction), ); auction.bids.push({ teamIndex: params.teamIndex, amount: params.amount, bidderUserId: team.captainUserId, timestamp: new Date(), }); await auction.save(); return auction; } public async markSold(params: MarkSoldParams): Promise { const auction = await this.getByMatchId(params.matchId); if (auction.phase !== 'bidding') { throw new BadRequestException('Auction is not in bidding phase.'); } if (!auction.currentBidderTeamIndex || auction.currentBid <= 0) { throw new BadRequestException('No bid to mark sold.'); } const team = this.findAuctionTeamByIndex( auction, auction.currentBidderTeamIndex, ); if (!team) throw new BadRequestException('Winning team not found.'); this.assertTeamHasSlot(team); const current = auction.order[auction.currentIndex]; if (!current) throw new BadRequestException('No current player.'); await this.recordSnapshot(auction, 'sold'); const preferredPrimary = current.preferredPositions[0]?.position; team.members.push({ userId: current.userId, assignedPosition: params.assignedPosition ?? preferredPrimary ?? 'MID', cost: auction.currentBid, }); team.points -= auction.currentBid; auction.phase = 'sold'; auction.currentDeadline = undefined; await auction.save(); return auction; } public async markPassed( matchId: mongoose.Types.ObjectId, ): Promise { const auction = await this.getByMatchId(matchId); if (auction.phase !== 'bidding') { throw new BadRequestException('Auction is not in bidding phase.'); } if (auction.currentBid > 0) { throw new BadRequestException('Cannot pass a player with an active bid.'); } const current = auction.order[auction.currentIndex]; if (!current) throw new BadRequestException('No current player.'); await this.recordSnapshot(auction, 'passed'); current.passCount = (current.passCount ?? 0) + 1; auction.passedQueue ??= []; auction.passedQueue.push(this.cloneAuctionPlayerSnapshot(current)); auction.phase = 'passed'; auction.currentDeadline = undefined; await auction.save(); return auction; } public async next( matchId: mongoose.Types.ObjectId, ): Promise { const auction = await this.getByMatchId(matchId); if ( auction.phase !== 'sold' && auction.phase !== 'presenting' && auction.phase !== 'passed' ) { throw new BadRequestException('Cannot advance from current phase.'); } const nextIndex = auction.currentIndex + 1; const completesAuction = nextIndex >= auction.order.length && (auction.passedQueue?.length ?? 0) === 0; await this.recordSnapshot(auction, completesAuction ? 'complete' : 'next'); if (nextIndex >= auction.order.length) { if ((auction.passedQueue?.length ?? 0) > 0) { auction.order.push( ...auction.passedQueue.map((player) => this.cloneAuctionPlayerSnapshot(player), ), ); auction.passedQueue = []; auction.auctionRound = (auction.auctionRound ?? 1) + 1; auction.currentIndex = nextIndex; auction.phase = 'presenting'; auction.currentBid = 0; auction.currentBidderTeamIndex = undefined; } else { auction.phase = 'complete'; auction.completedAt = new Date(); } } else { auction.currentIndex = nextIndex; auction.phase = 'presenting'; auction.currentBid = 0; auction.currentBidderTeamIndex = undefined; } auction.currentDeadline = undefined; await auction.save(); if (auction.phase === 'complete') { await this.syncMatchTeamsFromAuction(auction); } return auction; } public async reset(params: { matchId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId; }): Promise { const AuctionModel = await this.connectionService.getModel('auction'); const AuctionHistoryModel = await this.connectionService.getModel('auctionHistory'); const MatchModel = await this.connectionService.getModel('match'); const session = await this.connectionService.createSession(); if (!session) { throw new InternalServerErrorException('Failed to start DB session.'); } try { session.startTransaction(); const auction = await AuctionModel.findOne({ matchId: params.matchId, }).session(session); if (!auction) throw new NotFoundException('Auction not found.'); const match = await MatchModel.findById(params.matchId).session(session); if (!match) throw new NotFoundException('Match not found.'); if (!match.communityId.equals(params.communityId)) { throw new BadRequestException('Community mismatch.'); } await auction.deleteOne({ session }); await AuctionHistoryModel.deleteMany({ auctionId: auction._id }).session( session, ); if (match.status === 'team-built') { await this.tournamentCodeService.releaseFromMatch(match); match.status = 'recruiting'; match.teams = []; match.tournamentCodeIds = []; match.gameSchedule = []; match.participants.forEach((participant) => { participant.excluded = false; }); match.teamBuiltAt = undefined; match.result = undefined; match.resultPollState = undefined; await match.save({ session }); } await session.commitTransaction(); } catch (err) { await session.abortTransaction(); throw err; } finally { await session.endSession(); } } public async undoTo(params: { matchId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId; sequence: number; }): Promise { const AuctionModel = await this.connectionService.getModel('auction'); const AuctionHistoryModel = await this.connectionService.getModel('auctionHistory'); const MatchModel = await this.connectionService.getModel('match'); const session = await this.connectionService.createSession(); if (!session) { throw new InternalServerErrorException('Failed to start DB session.'); } try { session.startTransaction(); const auction = await AuctionModel.findOne({ matchId: params.matchId, }).session(session); if (!auction) throw new NotFoundException('Auction not found.'); const match = await MatchModel.findById(params.matchId).session(session); if (!match) throw new NotFoundException('Match not found.'); if (!match.communityId.equals(params.communityId)) { throw new BadRequestException('Community mismatch.'); } const history = await AuctionHistoryModel.findOne({ auctionId: auction._id, sequence: params.sequence, }) .session(session) .lean() .exec(); if (!history) throw new NotFoundException('Auction history not found.'); const snapshot = history.snapshotBefore; if (!snapshot || typeof snapshot !== 'object') { throw new BadRequestException('Auction history snapshot is invalid.'); } const undoingCompletedAuction = Boolean(auction.completedAt) && !('completedAt' in snapshot); if (undoingCompletedAuction) { await this.tournamentCodeService.releaseFromMatch(match); await this.tournamentResultService.cancelPolling(match); match.status = 'team-built'; match.result = undefined; await match.save({ session }); } await AuctionModel.replaceOne({ _id: auction._id }, snapshot, { session, }).exec(); await AuctionHistoryModel.deleteMany({ auctionId: auction._id, sequence: { $gt: params.sequence }, }) .session(session) .exec(); await session.commitTransaction(); const restored = await AuctionModel.findById(auction._id); if (!restored) throw new NotFoundException('Auction not found.'); return restored; } catch (err) { await session.abortTransaction(); throw err; } finally { await session.endSession(); } } private applyTopTierPriority( order: AuctionPlayerSnapshot[], threshold: AuctionTopTierThreshold, manualTopTierUserIds: mongoose.Types.ObjectId[], ): AuctionPlayerSnapshot[] { if (threshold === 'NONE') return order; if (threshold === 'MANUAL') { const manualIds = new Set( manualTopTierUserIds.map((userId) => userId.toString()), ); if (manualIds.size === 0) return order; const selected = order.filter((snap) => manualIds.has(snap.userId.toString()), ); const rest = order.filter( (snap) => !manualIds.has(snap.userId.toString()), ); return [...selected, ...rest]; } const ranks = [ 'IRON', 'BRONZE', 'SILVER', 'GOLD', 'PLATINUM', 'EMERALD', 'DIAMOND', 'MASTER', 'GRANDMASTER', 'CHALLENGER', ]; const cutoff = ranks.indexOf(threshold); const score = (snap: AuctionPlayerSnapshot) => { const solo = snap.tiers.find( (tier) => tier.queueType === 'RANKED_SOLO_5x5', ); if (!solo) return -1; const tierIdx = ranks.indexOf(solo.tier); if (tierIdx < cutoff) return -1; const rankBonus = ({ I: 4, II: 3, III: 2, IV: 1, '': 0 } as Record)[ solo.rank ] ?? 0; return tierIdx * 1000 + rankBonus * 100 + (solo.leaguePoints ?? 0) * 0.001; }; const top = order .filter((snap) => score(snap) >= 0) .sort((left, right) => score(right) - score(left)); const rest = order.filter((snap) => score(snap) < 0); return [...top, ...rest]; } private shuffleAuctionPlayerOrder( order: AuctionPlayerSnapshot[], ): AuctionPlayerSnapshot[] { const shuffled = [...order]; for (let index = shuffled.length - 1; index > 0; index -= 1) { const swapIndex = Math.floor(Math.random() * (index + 1)); [shuffled[index], shuffled[swapIndex]] = [ shuffled[swapIndex], shuffled[index], ]; } return shuffled; } private cloneAuctionPlayerSnapshot( player: AuctionPlayerSnapshot, ): AuctionPlayerSnapshot { return JSON.parse(JSON.stringify(player)) as AuctionPlayerSnapshot; } private normalizeChatMessage(message: string): string { const normalized = message.trim(); if (!normalized) { throw new BadRequestException('Chat message is required.'); } if (Array.from(normalized).length > AUCTION_CHAT_MAX_MESSAGE_LENGTH) { throw new BadRequestException( `Chat message must be ${AUCTION_CHAT_MAX_MESSAGE_LENGTH} characters or less.`, ); } return normalized; } private normalizeChatDisplayName(displayName: string | undefined): string { const normalized = displayName?.trim() || '관전자'; const chars = Array.from(normalized); if (chars.length <= AUCTION_CHAT_MAX_DISPLAY_NAME_LENGTH) { return normalized; } return chars.slice(0, AUCTION_CHAT_MAX_DISPLAY_NAME_LENGTH).join(''); } private async recordSnapshot( auction: AuctionDocument, action: AuctionActionType, actorUserId?: mongoose.Types.ObjectId, ): Promise { const AuctionHistoryModel = await this.connectionService.getModel('auctionHistory'); const latest = await AuctionHistoryModel.findOne({ auctionId: auction._id }) .sort({ sequence: -1 }) .select({ sequence: 1 }) .lean() .exec(); const snapshotBefore = typeof auction.toObject === 'function' ? auction.toObject({ depopulate: true }) : auction; await AuctionHistoryModel.create({ auctionId: auction._id, matchId: auction.matchId, sequence: (latest?.sequence ?? 0) + 1, action, actorUserId, snapshotBefore: JSON.parse(JSON.stringify(snapshotBefore)), takenAt: new Date(), }); } private formatHistoryActionLabel(action: AuctionActionType): string { switch (action) { case 'start': return '경매 시작'; case 'open-bidding': return '입찰 열기'; case 'bid': return '입찰'; case 'sold': return '낙찰 처리'; case 'passed': return '유찰'; case 'next': return '다음 선수'; case 'complete': return '경매 완료'; default: return action; } } private applyAuctionCut(match: { participants: MatchParticipant[]; }): MatchParticipant[] { const ordered = [...match.participants].sort( (left, right) => left.joinedAt.getTime() - right.joinedAt.getTime(), ); const desiredAuctionCount = Math.floor(ordered.length / 10) * 10; const activeIds = new Set( ordered .slice(0, desiredAuctionCount) .map((participant) => participant.userId.toString()), ); match.participants.forEach((participant) => { participant.excluded = !activeIds.has(participant.userId.toString()); }); return ordered.slice(0, desiredAuctionCount); } private assertCaptainAssignments( captains: StartAuctionParams['captains'], activeParticipants: Array<{ userId: mongoose.Types.ObjectId }>, expectedCaptainCount: number, ): void { const activeUserIds = new Set( activeParticipants.map((participant) => participant.userId.toString()), ); const captainUserIds = new Set(); const teamIndexes = new Set(); for (const captain of captains) { const userId = captain.userId.toString(); if (!activeUserIds.has(userId)) { throw new BadRequestException( 'All captains must be active participants of the match.', ); } if (captainUserIds.has(userId)) { throw new BadRequestException('Captains must be different users.'); } captainUserIds.add(userId); if ( !Number.isInteger(captain.teamIndex) || captain.teamIndex < 1 || captain.teamIndex > expectedCaptainCount ) { throw new BadRequestException('Captain teamIndex is out of range.'); } if (teamIndexes.has(captain.teamIndex)) { throw new BadRequestException('Duplicate captain team assignment.'); } teamIndexes.add(captain.teamIndex); } for (let teamIndex = 1; teamIndex <= expectedCaptainCount; teamIndex += 1) { if (!teamIndexes.has(teamIndex)) { throw new BadRequestException('Each teamIndex needs one captain.'); } } } private findAuctionTeamByIndex( auction: AuctionDocument, teamIndex: number, ): AuctionTeam | undefined { return auction.teams.find((team) => team.teamIndex === teamIndex); } private createDeadline(secondsFromNow: number): Date { return new Date(Date.now() + secondsFromNow * 1000); } private resolveBidExtensionSeconds(auction: AuctionDocument): number { const maxTimerSeconds = Math.max(5, auction.maxTimerSeconds ?? 30); const bidExtensionSeconds = Math.max(0, auction.bidExtensionSeconds ?? 5); const minimumRemainingSeconds = Math.min( maxTimerSeconds, bidExtensionSeconds, ); if (!auction.currentDeadline) { return maxTimerSeconds; } const remainingSeconds = Math.ceil( (auction.currentDeadline.getTime() - Date.now()) / 1000, ); return Math.min( maxTimerSeconds, Math.max(minimumRemainingSeconds, remainingSeconds), ); } private assertTeamHasSlot(team: AuctionTeam): void { if (this.countTeamMembersIncludingCaptain(team) >= AUCTION_MAX_TEAM_SIZE) { throw new BadRequestException('Team already has maximum members.'); } } private countTeamMembersIncludingCaptain(team: AuctionTeam): number { const userIds = new Set([team.captainUserId.toString()]); for (const member of team.members) { userIds.add(member.userId.toString()); } return userIds.size; } private async syncMatchTeamsFromAuction( auction: AuctionDocument, ): Promise { const MatchModel = await this.connectionService.getModel('match'); const match = await MatchModel.findById(auction.matchId); if (!match) throw new NotFoundException('Match not found.'); const participantByUserId = new Map( match.participants.map((participant) => [ participant.userId.toString(), participant, ]), ); match.teams = auction.teams.map((team) => { const captain = participantByUserId.get(team.captainUserId.toString()); const members: MatchTeamMember[] = [ { userId: team.captainUserId, assignedPosition: captain?.preferredPositions[0]?.position ?? 'MID', cost: 0, }, ...team.members .filter((member) => !member.userId.equals(team.captainUserId)) .map((member) => ({ userId: member.userId, assignedPosition: member.assignedPosition, cost: member.cost, })), ]; return { teamIndex: team.teamIndex, name: this.resolveTeamName(team.teamIndex), captainUserId: team.captainUserId, members, }; }); match.status = 'team-built'; match.teamBuiltAt = match.teamBuiltAt ?? new Date(); await match.save(); await this.tournamentCodeService.reserveForMatch(match); await this.tournamentResultService.scheduleInitialPoll(match); } private enqueueBackgroundOrderEnrichment(params: { auctionId: mongoose.Types.ObjectId; targets: AuctionEnrichmentTarget[]; platform: RiotPlatformRoute; region: RiotRegionalRoute; }): void { if (params.targets.length === 0) return; // 경매 시작 UX를 막지 않도록 Riot 최신화는 뒤에서 1명씩 천천히 수행한다. void this.refreshOrderSnapshotsFromRiot(params).catch((error: unknown) => { this.logger.warn( `Auction background Riot refresh failed for ${params.auctionId.toString()}: ${ error instanceof Error ? error.message : error }`, ); }); } private async refreshOrderSnapshotsFromRiot(params: { auctionId: mongoose.Types.ObjectId; targets: AuctionEnrichmentTarget[]; platform: RiotPlatformRoute; region: RiotRegionalRoute; }): Promise { const AuctionModel = await this.connectionService.getModel('auction'); this.logger.debug( `Refreshing Riot snapshots for ${params.targets.length} auction players in background.`, ); await runWithConcurrency( params.targets, AUCTION_BACKGROUND_ENRICHMENT_CONCURRENCY, async (target) => { try { const result = await this.enrichmentService.enrichRiotAccount({ userId: target.userId, puuid: target.puuid, options: { force: false, platform: params.platform, region: params.region, }, }); const account = result.account; if (!account) return; await AuctionModel.updateOne( { _id: params.auctionId, 'order.userId': target.userId, }, { $set: { 'order.$.gameName': account.gameName, 'order.$.tagLine': account.tagLine, 'order.$.profileIconId': account.profileIconId, 'order.$.tiers': account.tiers, 'order.$.masteries': account.championMasteries, 'order.$.recentStatsSummary': account.recentStatsSummary, updatedAt: new Date(), }, }, ).exec(); } catch (error: unknown) { this.logger.warn( `Failed to refresh auction Riot snapshot for ${target.puuid}: ${ error instanceof Error ? error.message : error }`, ); } }, ); } private wasRecentlyRefreshed(account: RiotAccount, cutoff: number): boolean { return this.getLatestRefreshAt(account) >= cutoff; } private getLatestRefreshAt(account: RiotAccount): number { const timestamps = [ account.lastRefreshRequestedAt, account.recentStatsFetchedAt, account.championMasteriesFetchedAt, account.matchIdsFetchedAt, ...account.tiers.map((tier) => tier.fetchedAt), ]; return timestamps.reduce((latest, value) => { const timestamp = value instanceof Date ? value.getTime() : 0; return Math.max(latest, timestamp); }, 0); } private resolveTeamName(teamIndex: number): string { return `${teamIndex}팀`; } } async function runWithConcurrency( items: T[], concurrency: number, worker: (item: T) => Promise, ): Promise { if (items.length === 0) return; const queue = [...items]; const runners = Array.from({ length: Math.min(concurrency, queue.length) }, async () => { while (queue.length > 0) { const item = queue.shift(); if (item === undefined) return; await worker(item); } }); await Promise.allSettled(runners); }