import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';

/**
 * unlock_condition JSON shape:
 *   { "type": "correct_answers", "count": 10 }
 *   { "type": "chapters_completed", "count": 1 }
 *   { "type": "level_completed", "levelOrder": 1 }
 */
@Injectable()
export class AchievementsService {
  constructor(private readonly prisma: PrismaService) {}

  async findAllForUser(userId: string) {
    const achievements = await this.prisma.achievement.findMany();
    const unlocked = await this.prisma.userAchievement.findMany({ where: { userId } });
    const unlockedIds = new Set(unlocked.map((u) => u.achievementId));

    return achievements.map((a) => ({
      id: a.id,
      title: a.title,
      description: a.description,
      icon: a.icon,
      unlocked: unlockedIds.has(a.id),
      unlockedAt: unlocked.find((u) => u.achievementId === a.id)?.unlockedAt ?? null,
    }));
  }

  async evaluateUnlocks(userId: string) {
    const achievements = await this.prisma.achievement.findMany();
    const already = await this.prisma.userAchievement.findMany({ where: { userId } });
    const alreadyIds = new Set(already.map((u) => u.achievementId));

    const correctAnswers = await this.prisma.userAnswer.count({ where: { userId, isCorrect: true } });
    const completedChapters = await this.prisma.userProgress.count({
      where: { userId, status: 'completed' },
    });

    for (const a of achievements) {
      if (alreadyIds.has(a.id)) continue;
      const cond = a.unlockCondition as Record<string, unknown>;
      let met = false;
      if (cond.type === 'correct_answers' && correctAnswers >= Number(cond.count)) met = true;
      if (cond.type === 'chapters_completed' && completedChapters >= Number(cond.count)) met = true;

      if (met) {
        await this.prisma.userAchievement.create({ data: { userId, achievementId: a.id } });
      }
    }
  }
}
