import { Injectable, NotFoundException } from '@nestjs/common'; import { METRICS, type AnalysisJobStatusDto, type MetricValueDto, type PlayerAnalysisDto, } from '@persona-lenz/shared'; import { ConnectionService } from '../global/database/connection.service'; import type { Account, AnalysisJob, PlayerProfile, TierInfo, } from '../global/database/schemas'; type JobStatusRecord = Pick< AnalysisJob, 'error' | 'jobId' | 'progress' | 'puuid' | 'stage' | 'status' >; type AccountSummaryRecord = Pick< Account, 'gameName' | 'profileIconId' | 'tagLine' | 'tiers' >; type PlayerProfileRecord = Pick< PlayerProfile, | 'championPool' | 'confidence' | 'featureSchemaVersion' | 'mainRole' | 'profile' | 'queueId' | 'sampleGameCount' | 'updatedAt' >; @Injectable() export class AnalysisReadService { constructor(private readonly connectionService: ConnectionService) {} public async getJobStatus(jobId: string): Promise { const analysisJobModel = await this.connectionService.getModel('analysisJob'); const job = await analysisJobModel .findOne({ jobId }) .lean() .exec(); if (!job) { throw new NotFoundException('Analysis job not found.'); } return { jobId: job.jobId, status: job.status, stage: job.stage, puuid: job.puuid, progress: job.progress, error: this.publicJobError(job.error), }; } public async getLatestPlayerAnalysis( puuid: string, queueId: number, ): Promise { const [account, profile] = await Promise.all([ this.findAccount(puuid), this.findPlayerProfile(puuid, queueId), ]); if (!account) { throw new NotFoundException('Player account not found.'); } if (!profile) { throw new NotFoundException('분석할 랭크 게임이 없음'); } return { account: { gameName: account.gameName, tagLine: account.tagLine, profileIconId: account.profileIconId, tiers: account.tiers.map((tier) => this.toTierDto(tier)), }, profile: { mainRole: profile.mainRole, queueId: profile.queueId, sampleGameCount: profile.sampleGameCount, championPool: profile.championPool, playstyle: Object.fromEntries( METRICS.map((metric) => [ metric.id, this.clampMetricValue(profile.profile[metric.id]), ]), ) as PlayerAnalysisDto['profile']['playstyle'], featureSchemaVersion: profile.featureSchemaVersion, confidence: profile.confidence, }, strengths: this.resolveMetricHighlights(profile.profile, 'strength'), weaknesses: this.resolveMetricHighlights(profile.profile, 'weakness'), updatedAt: profile.updatedAt.toISOString(), }; } private async findAccount( puuid: string, ): Promise { const accountModel = await this.connectionService.getModel('account'); return accountModel.findOne({ puuid }).lean().exec(); } private async findPlayerProfile( puuid: string, queueId: number, ): Promise { const playerProfileModel = await this.connectionService.getModel('playerProfile'); return playerProfileModel .findOne({ puuid, queueId }) .lean() .exec(); } private resolveMetricHighlights( profile: Record, direction: 'strength' | 'weakness', ): MetricValueDto[] { return METRICS.map((metric) => { const value = this.clampMetricValue(profile[metric.id]); return { metricId: metric.id, score: metric.direction === 'lowerIsBetter' ? 1 - value : value, value, }; }) .sort((left, right) => direction === 'strength' ? right.score - left.score : left.score - right.score, ) .slice(0, 3) .map(({ metricId, value }) => ({ metricId, value })); } private clampMetricValue(value: unknown): number { return typeof value === 'number' && Number.isFinite(value) ? Math.max(0, Math.min(1, value)) : 0; } private toTierDto( tier: TierInfo, ): PlayerAnalysisDto['account']['tiers'][number] { return { queueType: tier.queueType, tier: tier.tier, rank: tier.rank, leaguePoints: tier.leaguePoints, wins: tier.wins, losses: tier.losses, fetchedAt: tier.fetchedAt?.toISOString(), }; } private publicJobError(error: string | undefined): string | null { if (!error) return null; if ( error === 'Analysis failed during processing.' || error === 'Riot API key is invalid or expired.' || error === 'Riot account was not found for the selected region.' || error === 'Analysis could not be queued.' ) { return error; } return 'Analysis failed during processing.'; } }