import type { HallOfFameResponse, MatchDetailResponse, MatchEventType, MatchListResponse, MatchListView, } from '@lolympus/contracts'; import { BadRequestException, Body, Controller, Delete, Get, HttpCode, HttpStatus, Param, Patch, Post, Query, UseGuards, } from '@nestjs/common'; import { isISO8601 } from 'class-validator'; import mongoose from 'mongoose'; import { AllowPublicAccess } from '../auth/allow-public-access.decorator'; import { CurrentUser } from '../auth/current-user.decorator'; import { Roles } from '../auth/roles.decorator'; import { RolesGuard } from '../auth/roles.guard'; import { ParseObjectIdPipe } from '../common/parse-object-id.pipe'; import type { MatchStatus, UserDocument } from '../global/database/schema'; import { MATCH_EVENT_TYPES } from '../global/database/schema'; import { AddParticipantDto, CreateMatchDto, JoinMatchDto, UpdateMatchDto, UpdateParticipantDto, } from './dto/create-match.dto'; import { MatchService } from './match.service'; @Controller('communities/:communityId/matches') export class MatchController { constructor(private readonly matchService: MatchService) {} @Post() @Roles('admin', 'owner') @UseGuards(RolesGuard) public async createMatch( @CurrentUser() currentUser: UserDocument, @Param('communityId', ParseObjectIdPipe) communityId: mongoose.Types.ObjectId, @Body() body: CreateMatchDto, ): Promise { this.assertSameCommunity(currentUser, communityId); const match = await this.matchService.create({ communityId, hostUserId: currentUser._id, data: { title: body.title, eventType: body.eventType, description: body.description ?? '', mapId: body.mapId ?? 11, scheduledAt: body.scheduledAt, maxParticipants: body.maxParticipants ?? 10, gameCount: body.gameCount, gameMode: body.gameMode ?? 'pair', roundRobinMaxRounds: body.roundRobinMaxRounds, doubleEliminationResetFinalEnabled: body.doubleEliminationResetFinalEnabled, doubleEliminationGrandFinalGameCount: body.doubleEliminationGrandFinalGameCount, prizes: body.prizes ?? [], notices: body.notices ?? [], schedule: body.schedule ?? [], }, }); return this.matchService.serialize(match, { joined: false }); } // 공개 — 커뮤니티 내 매치 리스트. 로그인 시 본인 참여 여부를 함께 반환. @Get() @AllowPublicAccess() public async listMatches( @CurrentUser() currentUser: UserDocument | undefined, @Param('communityId', ParseObjectIdPipe) communityId: mongoose.Types.ObjectId, @Query('status') status?: MatchStatus, @Query('limit') limit?: string, @Query('page') page?: string, @Query('offset') offset?: string, @Query('scheduledFrom') scheduledFrom?: string, @Query('scheduledTo') scheduledTo?: string, @Query('sort') sort?: 'asc' | 'desc', @Query('includeResults') includeResults?: string, @Query('eventType') eventType?: MatchEventType, @Query('view') view?: MatchListView, @Query('asOf') asOf?: string, ): Promise { if (eventType !== undefined && !MATCH_EVENT_TYPES.includes(eventType)) { throw new BadRequestException('Invalid eventType.'); } if ( view !== undefined && view !== 'active' && view !== 'upcoming' && view !== 'history' ) { throw new BadRequestException('Invalid view.'); } if ( view && (status !== undefined || scheduledFrom !== undefined || scheduledTo !== undefined) ) { throw new BadRequestException( 'view cannot be combined with status or schedule filters.', ); } const asOfDate = this.toOptionalDate(asOf); if ( asOf !== undefined && (typeof asOf !== 'string' || !isISO8601(asOf, { strict: true, strictSeparator: true }) || !asOfDate) ) throw new BadRequestException('Invalid asOf.'); const result = await this.matchService.listPage({ communityId, status, eventType, limit: this.toOptionalNumber(limit), page: this.toOptionalNumber(page), offset: this.toOptionalNumber(offset), scheduledFrom: this.toOptionalDate(scheduledFrom), scheduledTo: this.toOptionalDate(scheduledTo), sort, ...(view ? { view, asOf: asOfDate } : {}), }); const historyResults = includeResults === 'true' ? await this.matchService.getHistoryResults(communityId, result.matches) : undefined; const eventProgress = view ? await this.matchService.getEventProgress(result.matches) : undefined; return { ...result, matches: result.matches.map((match) => { const summary = this.matchService.serialize(match, { ...(currentUser ? { joined: match.participants.some((participant) => participant.userId.equals(currentUser._id), ), } : {}), }); const historyResult = historyResults?.get(summary._id); return { ...summary, ...(historyResult ? { historyResult } : {}), ...(eventProgress ? { eventProgress: eventProgress.get(summary._id) } : {}), }; }), }; } @Get('hall-of-fame') @AllowPublicAccess() public getHallOfFame( @Param('communityId', ParseObjectIdPipe) communityId: mongoose.Types.ObjectId, ): Promise { return this.matchService.getHallOfFame(communityId); } @Get(':matchId') @AllowPublicAccess() public async getMatch( @CurrentUser() currentUser: UserDocument | undefined, @Param('communityId', ParseObjectIdPipe) communityId: mongoose.Types.ObjectId, @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, ): Promise { const match = await this.matchService.getById(matchId, communityId); const summary = this.matchService.serialize(match, { joined: Boolean( currentUser && match.participants.some((participant) => participant.userId.equals(currentUser._id), ), ), }); const progress = await this.matchService.getEventProgress([match]); return { ...summary, eventProgress: progress.get(summary._id) }; } @Patch(':matchId') @Roles('admin', 'owner') @UseGuards(RolesGuard) public async updateMatch( @CurrentUser() currentUser: UserDocument, @Param('communityId', ParseObjectIdPipe) communityId: mongoose.Types.ObjectId, @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, @Body() body: UpdateMatchDto, ): Promise { this.assertSameCommunity(currentUser, communityId); const match = await this.matchService.update({ matchId, communityId, patch: mongoose.omitUndefined({ ...body }), }); return this.matchService.serialize(match, { joined: match.participants.some((participant) => participant.userId.equals(currentUser._id), ), }); } @Delete(':matchId') @Roles('admin', 'owner') @UseGuards(RolesGuard) @HttpCode(HttpStatus.NO_CONTENT) public async deleteMatch( @CurrentUser() currentUser: UserDocument, @Param('communityId', ParseObjectIdPipe) communityId: mongoose.Types.ObjectId, @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, ) { this.assertSameCommunity(currentUser, communityId); await this.matchService.remove({ matchId, communityId }); } // 커뮤니티 멤버 본인 참여. 다른 유저 추가는 관리자 전용 경로를 사용한다. @Post(':matchId/participants') @Roles('owner', 'admin', 'member') @UseGuards(RolesGuard) public async joinMatch( @CurrentUser() currentUser: UserDocument, @Param('communityId', ParseObjectIdPipe) communityId: mongoose.Types.ObjectId, @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, @Body() body: JoinMatchDto, ): Promise { this.assertSameCommunity(currentUser, communityId); const match = await this.matchService.join({ matchId, communityId, userId: currentUser._id, preferredPositions: body.preferredPositions, }); return this.matchService.serialize(match, { joined: true }); } // 관리자 전용 — 커뮤니티 유저를 모집중 매치에 직접 추가한다. @Post(':matchId/participants/:userId') @Roles('admin', 'owner') @UseGuards(RolesGuard) public async addParticipant( @CurrentUser() currentUser: UserDocument, @Param('communityId', ParseObjectIdPipe) communityId: mongoose.Types.ObjectId, @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, @Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId, @Body() body: AddParticipantDto | undefined, ): Promise { this.assertSameCommunity(currentUser, communityId); const match = await this.matchService.join({ matchId, communityId, userId, preferredPositions: body?.preferredPositions, riotPuuid: body?.riotPuuid, }); return this.matchService.serialize(match, { joined: match.participants.some((participant) => participant.userId.equals(currentUser._id), ), }); } // 관리자 전용 — 참가자 주/부 포지션 변경. @Patch(':matchId/participants/:userId') @Roles('admin', 'owner') @UseGuards(RolesGuard) public async updateParticipant( @CurrentUser() currentUser: UserDocument, @Param('communityId', ParseObjectIdPipe) communityId: mongoose.Types.ObjectId, @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, @Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId, @Body() body: UpdateParticipantDto, ): Promise { this.assertSameCommunity(currentUser, communityId); const match = await this.matchService.updateParticipantPositions({ matchId, communityId, targetUserId: userId, mainPosition: body.mainPosition, subPosition: body.subPosition, }); return this.matchService.serialize(match, { joined: match.participants.some((participant) => participant.userId.equals(currentUser._id), ), }); } // 관리자 전용 — 참가자 강제 제외. @Delete(':matchId/participants') @Roles('admin', 'owner', 'member') @UseGuards(RolesGuard) public async cancelJoin( @CurrentUser() currentUser: UserDocument, @Param('communityId', ParseObjectIdPipe) communityId: mongoose.Types.ObjectId, @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, ): Promise { this.assertSameCommunity(currentUser, communityId); const match = await this.matchService.cancelJoin({ matchId, userId: currentUser._id, }); return this.matchService.serialize(match, { joined: false }); } @Delete(':matchId/participants/:userId') @Roles('admin', 'owner') @UseGuards(RolesGuard) @HttpCode(HttpStatus.NO_CONTENT) public async removeParticipant( @CurrentUser() currentUser: UserDocument, @Param('communityId', ParseObjectIdPipe) communityId: mongoose.Types.ObjectId, @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, @Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId, ) { this.assertSameCommunity(currentUser, communityId); await this.matchService.removeParticipant({ matchId, communityId, targetUserId: userId, }); } private assertSameCommunity( user: UserDocument, communityId: mongoose.Types.ObjectId, ): void { if (!user.communityId.equals(communityId)) { throw new BadRequestException('Different community.'); } } private toOptionalNumber(value?: string): number | undefined { const numberValue = Number(value); return Number.isFinite(numberValue) ? numberValue : undefined; } private toOptionalDate(value?: string): Date | undefined { if (!value) return undefined; const date = new Date(value); return Number.isNaN(date.getTime()) ? undefined : date; } }