import { Injectable, Logger } from '@nestjs/common';
import { OnEvent } from '@nestjs/event-emitter';
import { ReviewService } from './review.service';

@Injectable()
export class ReviewCardSubscriber {
  private readonly logger = new Logger(ReviewCardSubscriber.name);

  constructor(private readonly reviewService: ReviewService) {}

  @OnEvent('ai.analysis.completed')
  async handleAIAnalysisCompleted(payload: {
    userId: string;
    jobId: string;
    sessionId?: string;
    answerId?: string;
    type: string;
    score?: number;
    analysis?: Record<string, any>;
  }) {
    const { userId } = payload;
    this.logger.log(
      `Received ai.analysis.completed user=${userId} job=${payload.jobId} score=${payload.score}`,
    );

    if (!payload.analysis) return;

    try {
      const a = payload.analysis;
      const weaknesses = (a.weaknesses || []).join('；');
      const strengths = (a.strengths || []).join('；');
      const summary = a.summary || '';

      if (!weaknesses && !strengths) return;

      const title = summary ? summary.slice(0, 80) : 'AI 分析结果';
      const content = `摘要：${summary}\n\n掌握点：${strengths}\n\n薄弱点：${weaknesses}`;

      await this.reviewService.generateCards(userId, {
        knowledgeItemTitle: title,
        knowledgeItemContent: content,
        cardCount: Math.min(3, Math.max(1, (a.weaknesses?.length || 1))),
      });

      this.logger.log(
        `Generated review cards from analysis job=${payload.jobId} for user=${userId}`,
      );
    } catch (err: any) {
      this.logger.error(`Failed to generate review cards from analysis: ${err.message}`);
    }
  }
}
