import { BadRequestException, Injectable, InternalServerErrorException, Logger, NotFoundException, } from '@nestjs/common'; import mongoose from 'mongoose'; import { ConnectionService } from '../global/database/connection.service'; import { AuctionDocument, AuctionPlayerSnapshot, AuctionTeam, MatchParticipant, MatchTeamMember, Position, RiotAccount, TeamSide, } 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; interface StartAuctionParams { matchId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId; captains: { side: TeamSide; groupIndex: number; userId: mongoose.Types.ObjectId; }[]; initialPoints: number; maxTimerSeconds: number; } interface PlaceBidParams { matchId: mongoose.Types.ObjectId; side: TeamSide; groupIndex: number; amount: number; bidderUserId?: mongoose.Types.ObjectId; } interface MarkSoldParams { matchId: mongoose.Types.ObjectId; assignedPosition?: Position; } 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; const groupCount = expectedCaptainCount / 2; if (params.captains.length !== expectedCaptainCount) { throw new BadRequestException( `Expected ${expectedCaptainCount} captains for ${desiredAuctionCount} participants.`, ); } this.assertCaptainAssignments(params.captains, activeParticipants, groupCount); 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, }); } const auction = await AuctionModel.create({ matchId: params.matchId, phase: 'presenting', teams: params.captains.map((c) => ({ side: c.side, groupIndex: c.groupIndex, captainUserId: c.userId, points: params.initialPoints, members: [], })), order, currentIndex: 0, bids: [], currentBid: 0, maxTimerSeconds: params.maxTimerSeconds, initialPoints: params.initialPoints, startedAt: new Date(), }); match.status = 'team-built'; match.teamBuiltAt = match.teamBuiltAt ?? new Date(); await match.save(); await this.tournamentCodeService.reserveForMatch(match); await this.tournamentResultService.scheduleInitialPoll(match); 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 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.'); } auction.phase = 'bidding'; auction.currentBid = 0; auction.currentBidder = undefined; auction.currentBidderGroupIndex = 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.findAuctionTeam(auction, params.side, params.groupIndex); 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); // 임시 운영용: 클라이언트에서 선택한 팀장 모드를 신뢰하고 실제 로그인 사용자 검증은 건너뛴다. auction.currentBid = params.amount; auction.currentBidder = params.side; auction.currentBidderGroupIndex = params.groupIndex; auction.currentDeadline = this.createDeadline( this.resolveBidExtensionSeconds(auction), ); auction.bids.push({ side: params.side, groupIndex: params.groupIndex, 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.currentBidder || auction.currentBid <= 0) { throw new BadRequestException('No bid to mark sold.'); } const team = this.findAuctionTeam( auction, auction.currentBidder, auction.currentBidderGroupIndex ?? 1, ); 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.'); 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 next( matchId: mongoose.Types.ObjectId, ): Promise { const auction = await this.getByMatchId(matchId); if (auction.phase !== 'sold' && auction.phase !== 'presenting') { throw new BadRequestException('Cannot advance from current phase.'); } const nextIndex = auction.currentIndex + 1; if (nextIndex >= auction.order.length) { auction.phase = 'complete'; auction.completedAt = new Date(); } else { auction.currentIndex = nextIndex; auction.phase = 'presenting'; auction.currentBid = 0; auction.currentBidder = undefined; auction.currentBidderGroupIndex = 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 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 }); if (match.status === 'team-built') { await this.tournamentCodeService.releaseFromMatch(match); match.status = 'recruiting'; match.teams = []; match.tournamentCodeIds = []; 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(); } } 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 }>, groupCount: number, ): void { const activeUserIds = new Set( activeParticipants.map((participant) => participant.userId.toString()), ); const captainUserIds = new Set(); const teamKeys = new Set(); const requiredKeys = new Set(); for (let groupIndex = 1; groupIndex <= groupCount; groupIndex += 1) { requiredKeys.add(`blue:${groupIndex}`); requiredKeys.add(`red:${groupIndex}`); } 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 (captain.groupIndex < 1 || captain.groupIndex > groupCount) { throw new BadRequestException('Captain groupIndex is out of range.'); } const key = `${captain.side}:${captain.groupIndex}`; if (teamKeys.has(key)) { throw new BadRequestException('Duplicate captain team assignment.'); } teamKeys.add(key); } for (const key of requiredKeys) { if (!teamKeys.has(key)) { throw new BadRequestException('Each group needs one blue and one red captain.'); } } } private findAuctionTeam( auction: AuctionDocument, side: TeamSide, groupIndex: number, ): AuctionTeam | undefined { return auction.teams.find( (team) => team.side === side && (team.groupIndex ?? 1) === groupIndex, ); } private createDeadline(secondsFromNow: number): Date { return new Date(Date.now() + secondsFromNow * 1000); } private resolveBidExtensionSeconds(auction: AuctionDocument): number { if (!auction.currentDeadline) { return auction.maxTimerSeconds; } const remainingSeconds = Math.ceil( (auction.currentDeadline.getTime() - Date.now()) / 1000, ); return Math.max(5, 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 { side: team.side, groupIndex: team.groupIndex ?? 1, name: this.resolveTeamName(team.side, team.groupIndex ?? 1, auction.teams), 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( side: TeamSide, groupIndex: number, teams: AuctionTeam[], ): string { const groupCount = new Set(teams.map((team) => team.groupIndex ?? 1)).size; const sideLabel = side === 'blue' ? '블루팀' : '레드팀'; return groupCount <= 1 ? sideLabel : `${groupIndex}조 ${sideLabel}`; } } 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); }