import { BadRequestException, Injectable, NotFoundException, } from '@nestjs/common'; import mongoose from 'mongoose'; import { MatchService } from '../../match/match.service'; import { DakaoSegment } from '../dakao.types'; import { DakaoUserService } from '../dakao-user.service'; import { resolveRecruitingMatchReference } from './match-reference.util'; interface CancelHandlerParams { communityId: mongoose.Types.ObjectId; matchId: string; senderUserId: string; // kakaoTalkId senderNickname: string; // kakaoTalkNickname } @Injectable() export class MatchCancelHandler { constructor( private readonly matchService: MatchService, private readonly dakaoUserService: DakaoUserService, ) {} public async handle(params: CancelHandlerParams): Promise { const user = await this.dakaoUserService.findUserByKakaoTalkId({ communityId: params.communityId, kakaoTalkId: params.senderUserId, }); if (!user) { return this.errorReply( params, '먼저 !내전 계정등록 <닉네임>#<태그> 로 계정을 등록해주세요.', ); } const matchTarget = await this.resolveCancelTarget(params); if (typeof matchTarget === 'string') { return this.errorReply(params, matchTarget); } try { const match = await this.matchService.cancelJoin({ matchId: matchTarget, userId: user._id, }); return [ { kind: 'mention', userId: params.senderUserId, displayText: params.senderNickname, }, { kind: 'text', text: ` 참가 취소 완료 (${match.participants.length}/${match.maxParticipants})` + `\n내전: ${match.title}`, }, ]; } catch (err) { if (err instanceof NotFoundException) { return this.errorReply(params, '내전을 찾을 수 없습니다.'); } if (err instanceof BadRequestException) { return this.errorReply(params, this.translateBadRequest(err.message)); } throw err; } } private async resolveCancelTarget( params: CancelHandlerParams, ): Promise { if (mongoose.isValidObjectId(params.matchId)) { return new mongoose.Types.ObjectId(params.matchId); } const recruitingMatches = await this.matchService.list({ communityId: params.communityId, status: 'recruiting', limit: 50, }); if (recruitingMatches.length === 0) { return '모집 중인 내전이 없습니다.'; } const result = resolveRecruitingMatchReference( params.matchId, recruitingMatches, ); if (result.kind === 'matched') { return result.match._id; } if (result.kind === 'ambiguous') { return `내전 코드 또는 제목이 여러 개와 겹칩니다 (${result.titles.join(', ')}). 더 길게 입력하거나 ID를 사용해주세요.`; } return '모집 중인 내전을 찾을 수 없습니다. !내전 리스트에서 코드 또는 제목을 확인해주세요.'; } private errorReply( params: CancelHandlerParams, message: string, ): DakaoSegment[] { return [ { kind: 'mention', userId: params.senderUserId, displayText: params.senderNickname, }, { kind: 'text', text: ` ${message}` }, ]; } private translateBadRequest(raw: string): string { if (raw.includes('different communities')) { return '이 내전은 현재 채팅방의 커뮤니티 소속이 아닙니다.'; } if (raw.includes('not recruiting')) { return '모집 중인 내전만 참가 취소할 수 있습니다.'; } if (raw.includes('has not joined')) return '신청한 내전이 아닙니다.'; return raw; } }