import { BadRequestException, Injectable, InternalServerErrorException, NotFoundException, } from '@nestjs/common'; import mongoose from 'mongoose'; import { ConnectionService } from '../global/database/connection.service'; import { AuctionDocument, AuctionPlayerSnapshot, AuctionTeam, MatchTeamMember, Position, TeamSide, } from '../global/database/schema'; import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service'; import { TournamentCodeService } from '../tournament-code/tournament-code.service'; import { TournamentResultService } from '../tournament-result/tournament-result.service'; const AUCTION_MAX_TEAM_SIZE = 5; interface StartAuctionParams { matchId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId; captains: { side: TeamSide; userId: mongoose.Types.ObjectId }[]; initialPoints: number; maxTimerSeconds: number; } interface PlaceBidParams { matchId: mongoose.Types.ObjectId; side: TeamSide; amount: number; bidderUserId?: mongoose.Types.ObjectId; } interface MarkSoldParams { matchId: mongoose.Types.ObjectId; assignedPosition?: Position; } @Injectable() export class AuctionService { 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 captainUserIds = params.captains.map((c) => c.userId); if (captainUserIds[0].equals(captainUserIds[1])) { throw new BadRequestException('Captains must be different users.'); } const captainParticipants = match.participants.filter((p) => captainUserIds.some((cid) => cid.equals(p.userId)), ); if (captainParticipants.length !== 2) { throw new BadRequestException( 'Both captains must be participants of the match.', ); } if ( match.participants.length > params.captains.length * AUCTION_MAX_TEAM_SIZE ) { throw new BadRequestException( 'Auction supports up to 5 members per team including captains.', ); } const basePlayerUsers = await UserModel.find({ _id: { $in: match.participants .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 enrichTargets = basePlayerUsers .map((user) => ({ userId: user._id, puuid: (user.riotAccounts.find((account) => account.isPrimary) ?? user.riotAccounts[0]) ?.puuid, })) .filter((target): target is { userId: mongoose.Types.ObjectId; puuid: string } => typeof target.puuid === 'string' && target.puuid.length > 0, ); await runWithConcurrency(enrichTargets, 3, async (target) => { await this.enrichmentService.enrichRiotAccount({ userId: target.userId, puuid: target.puuid, options: { force: false, platform, region, }, }); }); const playerUsers = await UserModel.find({ _id: { $in: basePlayerUsers.map((user) => user._id) }, }); const userById = new Map(playerUsers.map((u) => [u._id.toString(), u])); const nonCaptainPuuids = new Set(); const order: AuctionPlayerSnapshot[] = []; for (const participant of match.participants) { 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, 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); 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.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 = auction.teams.find((t) => t.side === params.side); if (!team) throw new BadRequestException('Unknown team side.'); 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.currentDeadline = this.createDeadline( this.resolveBidExtensionSeconds(auction), ); auction.bids.push({ side: params.side, 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 = auction.teams.find((t) => t.side === auction.currentBidder); 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.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.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 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, name: this.resolveTeamName(team.side), 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 resolveTeamName(side: TeamSide): string { return side === 'blue' ? '블루팀' : '레드팀'; } } 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); }