import { BadRequestException, Injectable, InternalServerErrorException, NotFoundException, } from '@nestjs/common'; import mongoose from 'mongoose'; import { MatchStatsService } from '../community-stats/match-stats.service'; import { CommunityStatsService } from '../community-stats/community-stats.service'; import { ConnectionService } from '../global/database/connection.service'; import { Match, MatchDocument, MatchSeriesResult, MatchStatus, Position, PositionPreference, TierInfo, } from '../global/database/schema'; import { DEFAULT_TOURNAMENT_GAME_COUNT } from '../tournament-code/tournament-code.constants'; import { TournamentCodeService } from '../tournament-code/tournament-code.service'; const MATCH_SHORT_CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; const MATCH_SHORT_CODE_LENGTH = 4; const MATCH_SHORT_CODE_GENERATION_ATTEMPTS = 20; interface CreateMatchParams { communityId: mongoose.Types.ObjectId; hostUserId?: mongoose.Types.ObjectId; data: Partial & Pick; } interface UpdateMatchParams { matchId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId; patch: Partial; } interface ListMatchesQuery { communityId: mongoose.Types.ObjectId; status?: MatchStatus; limit?: number; } interface JoinMatchParams { matchId: mongoose.Types.ObjectId; userId: mongoose.Types.ObjectId; preferredPositions: PositionPreference[]; // 특정 RiotAccount(puuid)로 참가하고 싶을 때 지정. 없으면 primary 사용. riotPuuid?: string; } interface CancelMatchJoinParams { matchId: mongoose.Types.ObjectId; userId: mongoose.Types.ObjectId; } interface RemoveParticipantParams { matchId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId; targetUserId: mongoose.Types.ObjectId; } interface UpdateParticipantPositionsParams { matchId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId; targetUserId: mongoose.Types.ObjectId; mainPosition: Position; subPosition: Position; } @Injectable() export class MatchService { constructor( private readonly connectionService: ConnectionService, private readonly tournamentCodeService: TournamentCodeService, private readonly communityStatsService: CommunityStatsService, private readonly matchStatsService: MatchStatsService, ) {} public async create(params: CreateMatchParams): Promise { const MatchModel = await this.connectionService.getModel('match'); const CommunityModel = await this.connectionService.getModel('community'); const community = await CommunityModel.findById(params.communityId) .select({ matchGameCount: 1 }) .lean() .exec(); return MatchModel.create({ ...params.data, shortCode: params.data.shortCode ?? (await this.generateUniqueShortCode(MatchModel, params.communityId)), gameCount: params.data.gameCount ?? community?.matchGameCount ?? DEFAULT_TOURNAMENT_GAME_COUNT, communityId: params.communityId, hostUserId: params.hostUserId, }); } public async list(query: ListMatchesQuery): Promise { const MatchModel = await this.connectionService.getModel('match'); const filter: { communityId: mongoose.Types.ObjectId; status?: MatchStatus; } = { communityId: query.communityId, }; if (query.status) filter.status = query.status; return MatchModel.find(filter) .sort({ scheduledAt: -1 }) .limit(Math.min(query.limit ?? 50, 200)) .exec(); } public async ensureShortCode(match: MatchDocument): Promise { if (match.shortCode) return match; const MatchModel = await this.connectionService.getModel('match'); match.shortCode = await this.generateUniqueShortCode( MatchModel, match.communityId, ); await match.save(); return match; } public async getById( matchId: mongoose.Types.ObjectId, ): Promise { const MatchModel = await this.connectionService.getModel('match'); const match = await MatchModel.findById(matchId); if (!match) throw new NotFoundException('Match not found.'); return match; } public async serialize(match: MatchDocument) { const obj = match.toObject(); if (obj.result?.games) { obj.result.games = [...obj.result.games].sort( (left, right) => left.gameNumber - right.gameNumber, ); if (!obj.result.seriesResults?.length) { obj.result.seriesResults = this.buildSeriesResults(obj.result.games); } } return { ...obj, gameCount: match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT, gameMode: match.gameMode ?? 'pair', participants: (obj.participants ?? []).map((participant) => ({ ...participant, excluded: participant.excluded ?? false, })), teams: (obj.teams ?? []).map((team) => ({ ...team, })), gameSchedule: obj.gameSchedule ?? [], tournamentCodes: await this.tournamentCodeService.buildSlots(match), }; } public async update(params: UpdateMatchParams): Promise { const MatchModel = await this.connectionService.getModel('match'); 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 previousStatus = match.status; if ( previousStatus !== 'recruiting' && ('maxParticipants' in params.patch || 'gameMode' in params.patch) ) { throw new BadRequestException( 'maxParticipants and gameMode can only be changed while recruiting.', ); } match.set(params.patch); if (previousStatus !== 'recruiting' && match.status === 'recruiting') { if (match.tournamentCodeIds.length > 0) { await this.tournamentCodeService.releaseFromMatch(match); } match.tournamentCodeIds = []; match.gameSchedule = []; match.teamBuiltAt = undefined; match.result = undefined; match.resultPollState = undefined; } await match.save(); if (previousStatus !== 'recruiting' && match.status === 'recruiting') { await this.matchStatsService.removeByMatch(match._id); await this.communityStatsService.invalidateCommunity(params.communityId); } else if (match.result?.games?.length) { await this.matchStatsService.buildAndUpsert(match._id); await this.communityStatsService.invalidateCommunity(params.communityId); } return match; } public async remove(params: { matchId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId; }): Promise { const MatchModel = await this.connectionService.getModel('match'); 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.'); } await this.tournamentCodeService.releaseFromMatch(match); await this.matchStatsService.removeByMatch(match._id); await match.deleteOne(); await this.communityStatsService.invalidateCommunity(params.communityId); } public async join(params: JoinMatchParams): Promise { const MatchModel = await this.connectionService.getModel('match'); const UserModel = await this.connectionService.getModel('user'); const user = await UserModel.findById(params.userId); if (!user) throw new NotFoundException('User not found.'); const match = await MatchModel.findById(params.matchId); if (!match) throw new NotFoundException('Match not found.'); if (!match.communityId.equals(user.communityId)) { throw new BadRequestException( 'User and match belong to different communities.', ); } if (match.status !== 'recruiting') { throw new BadRequestException('Match is not recruiting.'); } if (match.participants.length >= match.maxParticipants) { throw new BadRequestException('Match is full.'); } const alreadyIn = match.participants.some((p) => p.userId.equals(user._id)); if (alreadyIn) { throw new BadRequestException('User already joined this match.'); } const selectedRiot = params.riotPuuid ? user.riotAccounts.find((a) => a.puuid === params.riotPuuid) : user.riotAccounts.find((a) => a.isPrimary); const selectedTier = this.selectParticipantTier(selectedRiot?.tiers ?? []); match.participants.push({ userId: user._id, puuid: selectedRiot?.puuid, gameName: selectedRiot?.gameName, tagLine: selectedRiot?.tagLine, profileIconId: selectedRiot?.profileIconId, tier: selectedTier, preferredPositions: params.preferredPositions, joinedAt: new Date(), excluded: false, }); await match.save(); return match; } public async cancelJoin( params: CancelMatchJoinParams, ): Promise { const MatchModel = await this.connectionService.getModel('match'); const UserModel = await this.connectionService.getModel('user'); const user = await UserModel.findById(params.userId); if (!user) throw new NotFoundException('User not found.'); const match = await MatchModel.findById(params.matchId); if (!match) throw new NotFoundException('Match not found.'); if (!match.communityId.equals(user.communityId)) { throw new BadRequestException( 'User and match belong to different communities.', ); } if (match.status !== 'recruiting') { throw new BadRequestException('Match is not recruiting.'); } const participantIndex = match.participants.findIndex((participant) => participant.userId.equals(user._id), ); if (participantIndex === -1) { throw new BadRequestException('User has not joined this match.'); } match.participants.splice(participantIndex, 1); await match.save(); return match; } // 관리자 전용 — 특정 참가자를 강제로 제외한다. public async removeParticipant( params: RemoveParticipantParams, ): Promise { const match = await this.loadRecruitingMatch( params.matchId, params.communityId, ); const participantIndex = match.participants.findIndex((participant) => participant.userId.equals(params.targetUserId), ); if (participantIndex === -1) { throw new NotFoundException('Participant not found.'); } match.participants.splice(participantIndex, 1); await match.save(); return match; } // 관리자 전용 — 참가자의 주/부 포지션(선호 우선순위 1·2)을 교체한다. public async updateParticipantPositions( params: UpdateParticipantPositionsParams, ): Promise { const match = await this.loadRecruitingMatch( params.matchId, params.communityId, ); const participant = match.participants.find((entry) => entry.userId.equals(params.targetUserId), ); if (!participant) { throw new NotFoundException('Participant not found.'); } participant.preferredPositions = this.reorderPreferredPositions( params.mainPosition, params.subPosition, participant.preferredPositions, ); match.markModified('participants'); await match.save(); return match; } private async loadRecruitingMatch( matchId: mongoose.Types.ObjectId, communityId: mongoose.Types.ObjectId, ): Promise { const MatchModel = await this.connectionService.getModel('match'); const match = await MatchModel.findById(matchId); if (!match) throw new NotFoundException('Match not found.'); if (!match.communityId.equals(communityId)) { throw new BadRequestException('Different community.'); } if (match.status !== 'recruiting') { throw new BadRequestException('Match is not recruiting.'); } return match; } // 주/부 포지션을 priority 1·2로 올리고 기존 나머지 선호는 뒤로 보존한다. private reorderPreferredPositions( mainPosition: Position, subPosition: Position, current: PositionPreference[], ): PositionPreference[] { const ordered: Position[] = [mainPosition]; if (subPosition !== mainPosition) ordered.push(subPosition); for (const preference of [...current].sort( (left, right) => left.priority - right.priority, )) { if (!ordered.includes(preference.position)) { ordered.push(preference.position); } } return ordered.map((position, index) => ({ position, priority: index + 1, })); } 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 async generateUniqueShortCode( MatchModel: mongoose.Model, communityId: mongoose.Types.ObjectId, ): Promise { for ( let attempt = 0; attempt < MATCH_SHORT_CODE_GENERATION_ATTEMPTS; attempt += 1 ) { const shortCode = this.generateShortCode(); const exists = await MatchModel.exists({ communityId, shortCode }); if (!exists) return shortCode; } throw new InternalServerErrorException( 'Failed to generate unique match short code.', ); } private generateShortCode(): string { let code = ''; for (let index = 0; index < MATCH_SHORT_CODE_LENGTH; index += 1) { const alphabetIndex = Math.floor( Math.random() * MATCH_SHORT_CODE_ALPHABET.length, ); code += MATCH_SHORT_CODE_ALPHABET[alphabetIndex]; } return code; } private buildSeriesResults( games: NonNullable['games'], ): MatchSeriesResult[] { const bySeries = new Map(); for (const game of games) { const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex); const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex); const key = `${teamAIndex}:${teamBIndex}`; const current = bySeries.get(key) ?? ({ teamAIndex, teamBIndex, teamAWins: 0, teamBWins: 0, } satisfies MatchSeriesResult); if (game.winnerTeamIndex === teamAIndex) current.teamAWins += 1; if (game.winnerTeamIndex === teamBIndex) current.teamBWins += 1; current.winnerTeamIndex = current.teamAWins > current.teamBWins ? teamAIndex : current.teamBWins > current.teamAWins ? teamBIndex : undefined; bySeries.set(key, current); } return [...bySeries.values()]; } }