import { BadRequestException, Body, Controller, Delete, Get, HttpCode, HttpStatus, Param, Patch, Post, Query, UseGuards, } from '@nestjs/common'; 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 { MatchDocument, MatchStatus, UserDocument, } 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, ) { this.assertSameCommunity(currentUser, communityId); return this.matchService.create({ communityId, hostUserId: currentUser._id, data: { title: body.title, description: body.description ?? '', mapId: body.mapId ?? 11, scheduledAt: body.scheduledAt, maxParticipants: body.maxParticipants ?? 10, gameCount: body.gameCount, gameMode: body.gameMode ?? 'pair', roundRobinMaxRounds: body.roundRobinMaxRounds, prizes: body.prizes ?? [], notices: body.notices ?? [], schedule: body.schedule ?? [], }, }); } // 공개 — 커뮤니티 내 매치 리스트. 로그인 시 본인 참여 여부를 함께 반환. @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', ) { const result = await this.matchService.listPage({ communityId, status, limit: this.toOptionalNumber(limit), page: this.toOptionalNumber(page), offset: this.toOptionalNumber(offset), scheduledFrom: this.toOptionalDate(scheduledFrom), scheduledTo: this.toOptionalDate(scheduledTo), sort, }); if (!currentUser) return result; const myId = currentUser._id; return { ...result, matches: result.matches.map((m) => this.annotateJoined(m, myId)), }; } @Get(':matchId') @AllowPublicAccess() public async getMatch( @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, ) { const match = await this.matchService.getById(matchId); return this.matchService.serialize(match); } @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, ) { this.assertSameCommunity(currentUser, communityId); return this.matchService.update({ matchId, communityId, patch: body }); } @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 }); } // 공개 — 참여 (로그인된 유저는 자기 자신, 비로그인은 body.userId 사용). @Post(':matchId/participants') @AllowPublicAccess() public async joinMatch( @CurrentUser() currentUser: UserDocument | undefined, @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, @Body() body: JoinMatchDto, ) { const userId = this.resolveJoinerUserId(currentUser, body.userId); return this.matchService.join({ matchId, userId, preferredPositions: body.preferredPositions, }); } // 관리자 전용 — 커뮤니티 유저를 모집중 매치에 직접 추가한다. @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, ) { this.assertSameCommunity(currentUser, communityId); const match = await this.matchService.join({ matchId, userId, preferredPositions: body?.preferredPositions, riotPuuid: body?.riotPuuid, }); return this.matchService.serialize(match); } // 관리자 전용 — 참가자 주/부 포지션 변경. @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, ) { 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); } // 관리자 전용 — 참가자 강제 제외. @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 resolveJoinerUserId( currentUser: UserDocument | undefined, bodyUserId?: string, ): mongoose.Types.ObjectId { if (currentUser) return currentUser._id; if (!bodyUserId || !mongoose.isValidObjectId(bodyUserId)) { throw new BadRequestException( 'userId is required when not authenticated.', ); } return new mongoose.Types.ObjectId(bodyUserId); } private annotateJoined( match: MatchDocument, userId: mongoose.Types.ObjectId, ) { const obj = match.toObject(); const joined = match.participants.some((p) => p.userId.equals(userId)); return { ...obj, joined }; } 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; } }