import { BadRequestException, ConflictException, 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, MatchStatus, POSITIONS, 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'; import { presentPublicMatch } from './match-public.presenter'; const MATCH_SHORT_CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; const MATCH_SHORT_CODE_LENGTH = 4; const MATCH_SHORT_CODE_GENERATION_ATTEMPTS = 20; const DEFAULT_MATCH_LIST_LIMIT = 50; const MAX_MATCH_LIST_LIMIT = 200; const DOUBLE_ELIMINATION_PARTICIPANT_COUNTS = [20, 40] as const; const DEFAULT_DOUBLE_ELIMINATION_SERIES_GAME_COUNT = 3; interface DoubleEliminationConfigInput { doubleEliminationResetFinalEnabled?: boolean; } interface CreateMatchParams { communityId: mongoose.Types.ObjectId; hostUserId?: mongoose.Types.ObjectId; data: Partial & Pick & DoubleEliminationConfigInput; } interface UpdateMatchParams { matchId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId; patch: Partial & DoubleEliminationConfigInput; } interface ListMatchesQuery { communityId: mongoose.Types.ObjectId; status?: MatchStatus; limit?: number; scheduledFrom?: Date; scheduledTo?: Date; sort?: 'asc' | 'desc'; } interface ListMatchesPageQuery extends ListMatchesQuery { page?: number; offset?: number; } interface MatchListFilter { communityId: mongoose.Types.ObjectId; status?: MatchStatus; scheduledAt?: { $gte?: Date; $lt?: Date; }; } interface JoinMatchParams { matchId: mongoose.Types.ObjectId; communityId?: 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(); const normalizedData = this.normalizeMatchConfig({ ...params.data, gameCount: params.data.gameCount ?? community?.matchGameCount ?? DEFAULT_TOURNAMENT_GAME_COUNT, }); return MatchModel.create({ ...normalizedData, shortCode: normalizedData.shortCode ?? (await this.generateUniqueShortCode(MatchModel, params.communityId)), communityId: params.communityId, hostUserId: params.hostUserId, }); } public async list(query: ListMatchesQuery): Promise { const MatchModel = await this.connectionService.getModel('match'); const filter = this.buildListFilter(query); return MatchModel.find(filter) .sort(this.buildListSort(query.sort)) .limit(this.normalizeListLimit(query.limit)) .exec(); } public async listPage(query: ListMatchesPageQuery): Promise<{ matches: MatchDocument[]; total: number; page: number; limit: number; }> { const MatchModel = await this.connectionService.getModel('match'); const filter = this.buildListFilter(query); const page = this.normalizeListPage(query.page); const limit = this.normalizeListLimit(query.limit); const offset = this.normalizeListOffset(query.offset); const skip = offset + (page - 1) * limit; const [matches, rawTotal] = await Promise.all([ MatchModel.find(filter) .sort(this.buildListSort(query.sort)) .skip(skip) .limit(limit) .exec(), MatchModel.countDocuments(filter).exec(), ]); return { matches, total: Math.max(rawTotal - offset, 0), page, limit, }; } 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, communityId: mongoose.Types.ObjectId, ): Promise { const MatchModel = await this.connectionService.getModel('match'); const match = await MatchModel.findOne({ _id: matchId, communityId }); if (!match) throw new NotFoundException('Match not found.'); return match; } public serialize(match: MatchDocument, options: { joined?: boolean } = {}) { const obj = match.toObject(); return presentPublicMatch( { ...obj, gameCount: match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT, gameMode: match.gameMode ?? 'pair', } as never, options, ); } 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' && params.patch.status === 'recruiting' ) { throw new ConflictException( 'A finalized team build cannot return to recruiting. Preserve its immutable lifecycle and create a new Match instead.', ); } if ( previousStatus !== 'recruiting' && ('maxParticipants' in params.patch || 'gameCount' in params.patch || 'gameMode' in params.patch || 'roundRobinMaxRounds' in params.patch || 'doubleEliminationResetFinalEnabled' in params.patch) ) { throw new BadRequestException( 'maxParticipants, gameCount, gameMode, roundRobinMaxRounds, and doubleEliminationResetFinalEnabled can only be changed while recruiting.', ); } const patchToSet = previousStatus === 'recruiting' ? this.normalizeMatchConfig({ ...params.patch, gameMode: params.patch.gameMode ?? match.gameMode, maxParticipants: params.patch.maxParticipants ?? match.maxParticipants, gameCount: params.patch.gameCount ?? match.gameCount, roundRobinMaxRounds: params.patch.roundRobinMaxRounds ?? match.roundRobinMaxRounds, doubleEliminationResetFinalEnabled: params.patch.doubleEliminationResetFinalEnabled ?? params.patch.doubleElimination?.resetFinalEnabled ?? match.doubleElimination?.resetFinalEnabled, }) : this.stripMatchConfigInput(params.patch); match.set(patchToSet); await match.save(); 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.'); } if (match.status !== 'recruiting') { throw new ConflictException( 'Only a recruiting Match can be hard-deleted. Finalized Match history must be preserved.', ); } if (match.competitionId) { throw new ConflictException( 'A Match with a Competition cannot be hard-deleted. Preserve the immutable ledger and archive the Match instead.', ); } 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.'); if (params.communityId && !user.communityId.equals(params.communityId)) { throw new NotFoundException('Match not found.'); } const selectedRiot = params.riotPuuid ? user.riotAccounts.find((a) => a.puuid === params.riotPuuid) : user.riotAccounts.find((a) => a.isPrimary); const selectedTier = this.selectParticipantTier(selectedRiot?.tiers ?? []); const participant = { userId: user._id, puuid: selectedRiot?.puuid, gameName: selectedRiot?.gameName, tagLine: selectedRiot?.tagLine, profileIconId: selectedRiot?.profileIconId, tier: selectedTier, preferredPositions: this.resolveJoinPreferredPositions( params.preferredPositions, user.preferredPositions, ), joinedAt: new Date(), excluded: false, }; const updatedMatch = await MatchModel.findOneAndUpdate( { _id: params.matchId, communityId: params.communityId ?? user.communityId, status: 'recruiting', 'participants.userId': { $ne: user._id }, $expr: { $lt: [{ $size: '$participants' }, '$maxParticipants'] }, }, { $push: { participants: participant } }, { returnDocument: 'after', runValidators: true }, ); if (updatedMatch) return updatedMatch; return await this.throwJoinFailure(MatchModel, params.matchId, user); } private normalizeMatchConfig< T extends Partial & DoubleEliminationConfigInput, >(input: T): Partial { const patch = this.stripMatchConfigInput(input); const gameMode = patch.gameMode ?? 'pair'; const maxParticipants = patch.maxParticipants ?? 10; if (gameMode === 'double-elimination') { if ( !DOUBLE_ELIMINATION_PARTICIPANT_COUNTS.includes( maxParticipants as (typeof DOUBLE_ELIMINATION_PARTICIPANT_COUNTS)[number], ) ) { throw new BadRequestException( 'Double elimination supports only 20 or 40 participants.', ); } return { ...patch, gameMode, maxParticipants, gameCount: this.normalizeDoubleEliminationSeriesGameCount( patch.gameCount ?? DEFAULT_DOUBLE_ELIMINATION_SERIES_GAME_COUNT, ), roundRobinMaxRounds: undefined, gameSchedule: [], doubleElimination: { teamCount: (maxParticipants / 5) as 4 | 8, resetFinalEnabled: input.doubleEliminationResetFinalEnabled ?? input.doubleElimination?.resetFinalEnabled ?? false, resetFinalCreated: false, seeds: [], bracketMatches: [], placements: {}, events: [], }, }; } return { ...patch, gameMode, doubleElimination: undefined, }; } private stripMatchConfigInput< T extends Partial & DoubleEliminationConfigInput, >(input: T): Partial { const patch = { ...input }; delete patch.doubleEliminationResetFinalEnabled; return patch; } private normalizeDoubleEliminationSeriesGameCount(gameCount: number): number { if (!Number.isInteger(gameCount) || gameCount < 1) { return DEFAULT_DOUBLE_ELIMINATION_SERIES_GAME_COUNT; } return gameCount % 2 === 0 ? gameCount + 1 : gameCount; } 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 updatedMatch = await MatchModel.findOneAndUpdate( { _id: params.matchId, communityId: user.communityId, status: 'recruiting', 'participants.userId': user._id, }, { $pull: { participants: { userId: user._id } } }, { returnDocument: 'after', runValidators: true }, ); if (updatedMatch) return updatedMatch; return await this.throwCancelJoinFailure(MatchModel, params.matchId, user); } // 관리자 전용 — 특정 참가자를 강제로 제외한다. public async removeParticipant( params: RemoveParticipantParams, ): Promise { const MatchModel = await this.connectionService.getModel('match'); const updatedMatch = await MatchModel.findOneAndUpdate( { _id: params.matchId, communityId: params.communityId, status: 'recruiting', 'participants.userId': params.targetUserId, }, { $pull: { participants: { userId: params.targetUserId } } }, { returnDocument: 'after', runValidators: true }, ); if (updatedMatch) return updatedMatch; const match = await this.loadRecruitingMatch( params.matchId, params.communityId, ); if ( !match.participants.some((participant) => this.sameObjectId(participant.userId, params.targetUserId), ) ) { throw new NotFoundException('Participant not found.'); } throw new BadRequestException('Participant could not be removed.'); } // 관리자 전용 — 참가자의 주/부 포지션(선호 우선순위 1·2)을 교체한다. public async updateParticipantPositions( params: UpdateParticipantPositionsParams, ): Promise { const MatchModel = await this.connectionService.getModel('match'); 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.'); } const preferredPositions = this.reorderPreferredPositions( params.mainPosition, params.subPosition, participant.preferredPositions, ); const updatedMatch = await MatchModel.findOneAndUpdate( { _id: params.matchId, communityId: params.communityId, status: 'recruiting', 'participants.userId': params.targetUserId, }, { $set: { 'participants.$[participant].preferredPositions': preferredPositions, }, }, { arrayFilters: [{ 'participant.userId': params.targetUserId }], returnDocument: 'after', runValidators: true, }, ); if (!updatedMatch) { throw new BadRequestException( 'Participant positions could not be updated.', ); } return updatedMatch; } 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; } private async throwJoinFailure( MatchModel: mongoose.Model, matchId: mongoose.Types.ObjectId, user: { _id: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId; }, ): Promise { const match = await MatchModel.findById(matchId); if (!match) throw new NotFoundException('Match not found.'); if (!this.sameObjectId(match.communityId, 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.some((participant) => this.sameObjectId(participant.userId, user._id), ) ) { throw new BadRequestException('User already joined this match.'); } if (match.participants.length >= match.maxParticipants) { throw new BadRequestException('Match is full.'); } throw new BadRequestException('Unable to join this match.'); } private async throwCancelJoinFailure( MatchModel: mongoose.Model, matchId: mongoose.Types.ObjectId, user: { _id: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId; }, ): Promise { const match = await MatchModel.findById(matchId); if (!match) throw new NotFoundException('Match not found.'); if (!this.sameObjectId(match.communityId, 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.some((participant) => this.sameObjectId(participant.userId, user._id), ) ) { throw new BadRequestException('User has not joined this match.'); } throw new BadRequestException('Unable to cancel match join.'); } private sameObjectId( left: mongoose.Types.ObjectId | { toString(): string }, right: mongoose.Types.ObjectId | { toString(): string }, ): boolean { if (left instanceof mongoose.Types.ObjectId) { return left.equals(right.toString()); } return left.toString() === right.toString(); } // 주/부 포지션을 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 resolveJoinPreferredPositions( requested: PositionPreference[] | undefined, saved: PositionPreference[] | undefined, ): PositionPreference[] { const source = requested?.length ? requested : saved?.length ? saved : POSITIONS.map((position, index) => ({ position, priority: index + 1, })); return [...source] .sort((left, right) => left.priority - right.priority) .slice(0, 5) .map((preference, index) => ({ position: preference.position, priority: index + 1, })); } private buildListFilter(query: ListMatchesQuery): MatchListFilter { const filter: MatchListFilter = { communityId: query.communityId, }; if (query.status) filter.status = query.status; if (query.scheduledFrom || query.scheduledTo) { filter.scheduledAt = {}; if (query.scheduledFrom) filter.scheduledAt.$gte = query.scheduledFrom; if (query.scheduledTo) filter.scheduledAt.$lt = query.scheduledTo; } return filter; } private buildListSort(sort?: 'asc' | 'desc'): { scheduledAt: 1 | -1 } { return { scheduledAt: sort === 'asc' ? 1 : -1 }; } private normalizeListLimit(limit?: number): number { if (!Number.isFinite(limit) || !limit || limit < 1) { return DEFAULT_MATCH_LIST_LIMIT; } return Math.min(Math.floor(limit), MAX_MATCH_LIST_LIMIT); } private normalizeListPage(page?: number): number { if (!Number.isFinite(page) || !page || page < 1) { return 1; } return Math.floor(page); } private normalizeListOffset(offset?: number): number { if (!Number.isFinite(offset) || !offset || offset < 1) { return 0; } return Math.floor(offset); } 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; } }