import { Injectable, Logger } from '@nestjs/common'; import mongoose, { isValidObjectId } from 'mongoose'; import { ConnectionService } from '../global/database/connection.service'; import { Position, PositionPreference, RiotAccount, UserDocument, } from '../global/database/schema'; import { RiotApiError } from '../riot/riot.client.service'; import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service'; import { RiotAccountService } from '../riot/riot-account.service'; import { RIOT_PLATFORM_ROUTES, RIOT_REGIONAL_ROUTES, RiotPlatformRoute, RiotRegionalRoute, } from '../riot/riot.types'; import { formatCodePoints, normalizeRiotIdPart } from './riot-id.util'; export class DakaoUserError extends Error { constructor( public readonly code: | 'invalid_project_id' | 'community_not_found' | 'riot_account_not_found' | 'riot_account_already_registered' | 'riot_account_conflict' | 'riot_account_lookup_failed', public readonly detail?: string, ) { super(`Dakao user error: ${code}${detail ? ` (${detail})` : ''}`); } } interface ResolveContext { communityId: mongoose.Types.ObjectId; kakaoTalkId: string; kakaoTalkNickname: string; gameName: string; tagLine: string; } interface ResolveResult { user: UserDocument; riotAccount: RiotAccount; } interface RiotRouting { platform: RiotPlatformRoute; region: RiotRegionalRoute; } interface ResolvedRiotIdentity { requestedGameName: string; requestedTagLine: string; dto: { puuid: string; gameName: string | null; tagLine: string | null }; } const DEFAULT_RIOT_PLATFORM: RiotPlatformRoute = 'kr'; const DEFAULT_RIOT_REGION: RiotRegionalRoute = 'asia'; @Injectable() export class DakaoUserService { private readonly logger = new Logger(DakaoUserService.name); constructor( private readonly connectionService: ConnectionService, private readonly riotAccountService: RiotAccountService, private readonly enrichmentService: RiotAccountEnrichmentService, ) {} public async resolveCommunityIdByDakaoProjectId( dakaoProjectId: string, ): Promise { if (!isValidObjectId(dakaoProjectId)) { throw new DakaoUserError('invalid_project_id', dakaoProjectId); } const CommunityModel = await this.connectionService.getModel('community'); const community = await CommunityModel.findOne({ dakaoProjectId: dakaoProjectId, }) .select({ _id: 1 }) .lean() .exec(); if (!community) { throw new DakaoUserError('community_not_found', dakaoProjectId); } return community._id as mongoose.Types.ObjectId; } public async upsertUser(params: { communityId: mongoose.Types.ObjectId; kakaoTalkId: string; kakaoTalkNickname: string; }): Promise { const UserModel = await this.connectionService.getModel('user'); const user = await UserModel.findOneAndUpdate( { communityId: params.communityId, kakaoTalkId: params.kakaoTalkId }, { $set: { kakaoTalkNickname: params.kakaoTalkNickname }, $setOnInsert: { communityId: params.communityId, kakaoTalkId: params.kakaoTalkId, role: 'member', isActivated: true, }, }, { upsert: true, returnDocument: 'after', setDefaultsOnInsert: true }, ).exec(); if (!user) { // upsert + returnDocument='after' 이면 항상 반환되지만 타입 안전을 위해 가드. throw new DakaoUserError('community_not_found'); } return user; } public async findUserByKakaoTalkId(params: { communityId: mongoose.Types.ObjectId; kakaoTalkId: string; }): Promise { const UserModel = await this.connectionService.getModel('user'); return UserModel.findOne({ communityId: params.communityId, kakaoTalkId: params.kakaoTalkId, }).exec(); } public async resolveRiotAccount( context: ResolveContext, ): Promise { const user = await this.upsertUser(context); const routing = await this.resolveRiotRouting(context.communityId); const { requestedGameName, requestedTagLine, dto } = await this.lookupRiotIdentity(context, routing); const nextGameName = dto.gameName ?? requestedGameName; const nextTagLine = dto.tagLine ?? requestedTagLine; const existing = user.riotAccounts.find( (a) => a.gameName.toLowerCase() === requestedGameName.toLowerCase() && a.tagLine.toLowerCase() === requestedTagLine.toLowerCase(), ); if (existing) { this.logger.log( `Found existing Riot account ${requestedGameName}#${requestedTagLine}: puuid=${existing.puuid}`, ); } if (existing) { if (existing.puuid !== dto.puuid) { this.logger.warn( `Riot account puuid mismatch for ${requestedGameName}#${requestedTagLine}: stored=${existing.puuid} resolved=${dto.puuid}. Updating stored account.`, ); existing.puuid = dto.puuid; existing.gameName = nextGameName; existing.tagLine = nextTagLine; this.clearRiotCache(existing); await this.saveUserHandlingDuplicate(user, nextGameName, nextTagLine); return this.enrichAttachedAccount({ user, riotAccount: existing, platform: routing.platform, region: routing.region, }); } if ( existing.gameName !== nextGameName || existing.tagLine !== nextTagLine ) { existing.gameName = nextGameName; existing.tagLine = nextTagLine; await user.save(); } return { user, riotAccount: existing }; } const existingByPuuid = user.riotAccounts.find( (account) => account.puuid === dto.puuid, ); if (existingByPuuid) { if ( existingByPuuid.gameName !== nextGameName || existingByPuuid.tagLine !== nextTagLine ) { existingByPuuid.gameName = nextGameName; existingByPuuid.tagLine = nextTagLine; await user.save(); } return { user, riotAccount: existingByPuuid }; } return this.attachRiotAccount({ user, puuid: dto.puuid, gameName: nextGameName, tagLine: nextTagLine, platform: routing.platform, region: routing.region, }); } public async registerRiotAccount( context: ResolveContext, ): Promise { return this.resolveRiotAccount(context); } public async registerPrimaryRiotAccount( context: ResolveContext, ): Promise { return this.registerRiotAccount(context); } public async registerPreferredPositions(params: { communityId: mongoose.Types.ObjectId; kakaoTalkId: string; kakaoTalkNickname: string; positions: Position[]; }): Promise { const user = await this.upsertUser({ communityId: params.communityId, kakaoTalkId: params.kakaoTalkId, kakaoTalkNickname: params.kakaoTalkNickname, }); user.preferredPositions = this.toPositionPreferences(params.positions); await user.save(); return user; } public async changePrimaryRiotAccount( context: ResolveContext, ): Promise { const requestedGameName = normalizeRiotIdPart(context.gameName); const requestedTagLine = normalizeRiotIdPart(context.tagLine); const detail = `${requestedGameName}#${requestedTagLine}`; const user = await this.findUserByKakaoTalkId({ communityId: context.communityId, kakaoTalkId: context.kakaoTalkId, }); if (!user) { throw new DakaoUserError('riot_account_not_found', detail); } const target = user.riotAccounts.find( (account) => normalizeRiotIdPart(account.gameName).toLowerCase() === requestedGameName.toLowerCase() && normalizeRiotIdPart(account.tagLine).toLowerCase() === requestedTagLine.toLowerCase(), ); if (!target) { throw new DakaoUserError('riot_account_not_found', detail); } if (context.kakaoTalkNickname.trim()) { user.kakaoTalkNickname = context.kakaoTalkNickname; } for (const account of user.riotAccounts) { account.isPrimary = account.puuid === target.puuid; } await user.save(); return { user, riotAccount: target }; } private toPositionPreferences(positions: Position[]): PositionPreference[] { return positions.map((position, index) => ({ position, priority: index + 1, })); } private async lookupRiotIdentity( context: ResolveContext, routing: RiotRouting, ): Promise { const requestedGameName = normalizeRiotIdPart(context.gameName); const requestedTagLine = normalizeRiotIdPart(context.tagLine); this.logRiotIdNormalization(context, requestedGameName, requestedTagLine); try { const dto = await this.riotAccountService.getByRiotId( requestedGameName, requestedTagLine, { region: routing.region }, ); this.logger.log( `Resolved Riot ID ${requestedGameName}#${requestedTagLine} via ${routing.region}: puuid=${dto.puuid} canonical=${dto.gameName ?? '-'}#${dto.tagLine ?? '-'}`, ); return { requestedGameName, requestedTagLine, dto }; } catch (err) { if (err instanceof RiotApiError && err.status === 404) { throw new DakaoUserError( 'riot_account_not_found', `${requestedGameName}#${requestedTagLine}`, ); } this.logger.error( `Riot account lookup failed for ${requestedGameName}#${requestedTagLine}: ${ (err as Error)?.message ?? err }`, ); throw new DakaoUserError( 'riot_account_lookup_failed', (err as Error)?.message, ); } } private logRiotIdNormalization( context: ResolveContext, normalizedGameName: string, normalizedTagLine: string, ): void { if ( context.gameName === normalizedGameName && context.tagLine === normalizedTagLine ) { return; } this.logger.warn( `Normalized Riot ID input ${context.gameName}#${context.tagLine} -> ${normalizedGameName}#${normalizedTagLine} ` + `(gameNameCodePoints=${formatCodePoints(context.gameName)}, tagLineCodePoints=${formatCodePoints(context.tagLine)})`, ); } private async resolveRiotRouting( communityId: mongoose.Types.ObjectId, ): Promise { const CommunityModel = await this.connectionService.getModel('community'); const community = await CommunityModel.findById(communityId) .select({ riotPlatform: 1, riotRegion: 1 }) .lean() .exec(); return { platform: this.toRiotPlatform(community?.riotPlatform), region: this.toRiotRegion(community?.riotRegion), }; } private async attachRiotAccount(params: { user: UserDocument; puuid: string; gameName: string; tagLine: string; platform: RiotPlatformRoute; region: RiotRegionalRoute; }): Promise { const { user } = params; const isFirst = user.riotAccounts.length === 0; user.riotAccounts.push({ puuid: params.puuid, gameName: params.gameName, tagLine: params.tagLine, profileIconId: 0, revisionDate: 0, summonerLevel: 0, isPrimary: isFirst, tiers: [], tierHistory: [], matchIds: [], championMasteries: [], championRecords: {}, } as unknown as RiotAccount); await this.saveUserHandlingDuplicate(user, params.gameName, params.tagLine); const attached = user.riotAccounts.find((a) => a.puuid === params.puuid); if (!attached) { throw new DakaoUserError('riot_account_lookup_failed', 'attach failed'); } return this.enrichAttachedAccount({ user, riotAccount: attached, platform: params.platform, region: params.region, }); } private async enrichAttachedAccount(params: { user: UserDocument; riotAccount: RiotAccount; platform: RiotPlatformRoute; region: RiotRegionalRoute; }): Promise { // 외부 API 실패는 등록 자체를 막지 않음. try { const enrichResult = await this.enrichmentService.enrichRiotAccount({ userId: params.user._id, puuid: params.riotAccount.puuid, options: { force: true, platform: params.platform, region: params.region, }, }); if (enrichResult.account) { return { user: params.user, riotAccount: enrichResult.account }; } } catch (err) { this.logger.warn( `Riot enrichment failed (continuing with empty data): ${ (err as Error)?.message ?? err }`, ); } return { user: params.user, riotAccount: params.riotAccount }; } private async saveUserHandlingDuplicate( user: UserDocument, gameName: string, tagLine: string, ): Promise { try { await user.save(); } catch (err) { // 같은 communityId + puuid 중복은 다른 유저가 이미 등록한 케이스. if ((err as { code?: number })?.code === 11000) { throw new DakaoUserError( 'riot_account_conflict', `${gameName}#${tagLine}`, ); } throw err; } } private clearRiotCache(account: RiotAccount): void { account.profileIconId = 0; account.revisionDate = 0; account.summonerLevel = 0; account.tiers = []; account.tierHistory = []; account.matchIds = []; account.matchIdsFetchedAt = undefined; account.recentStatsSummary = undefined; account.recentStatsFetchedAt = undefined; account.championMasteries = []; account.championMasteriesFetchedAt = undefined; account.championRecords = {}; account.championRecordsFetchedAt = undefined; } private toRiotPlatform(value: unknown): RiotPlatformRoute { return typeof value === 'string' && RIOT_PLATFORM_ROUTES.includes(value as RiotPlatformRoute) ? (value as RiotPlatformRoute) : DEFAULT_RIOT_PLATFORM; } private toRiotRegion(value: unknown): RiotRegionalRoute { return typeof value === 'string' && RIOT_REGIONAL_ROUTES.includes(value as RiotRegionalRoute) ? (value as RiotRegionalRoute) : DEFAULT_RIOT_REGION; } }