import { BadRequestException, Injectable, NotFoundException, } from '@nestjs/common'; import mongoose from 'mongoose'; import { CommunityStatsService } from '../community-stats/community-stats.service'; import { ConnectionService } from '../global/database/connection.service'; import { Match, MatchDocument, MatchSeriesResult, MatchStatus, 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'; 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; } @Injectable() export class MatchService { constructor( private readonly connectionService: ConnectionService, private readonly tournamentCodeService: TournamentCodeService, private readonly communityStatsService: CommunityStatsService, ) {} 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, 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 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, })), 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' && match.tournamentCodeIds.length > 0 ) { await this.tournamentCodeService.releaseFromMatch(match); match.tournamentCodeIds = []; match.teamBuiltAt = undefined; match.result = undefined; match.resultPollState = undefined; } await match.save(); 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 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; } 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 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()]; } }