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

@Injectable()
export class ChaptersService {
  constructor(private readonly prisma: PrismaService) {}

  async findAll(userId: string, levelId?: string) {
    const chapters = await this.prisma.chapter.findMany({
      where: levelId ? { levelId } : undefined,
      orderBy: [{ levelId: 'asc' }, { orderInLevel: 'asc' }],
      include: { _count: { select: { questions: true } } },
    });
    const progressRows = await this.prisma.userProgress.findMany({ where: { userId } });
    const progressByChapter = new Map(progressRows.map((p) => [p.chapterId, p]));

    return chapters.map((ch) => ({
      id: ch.id,
      levelId: ch.levelId,
      title: ch.title,
      description: ch.description,
      teaser: ch.teaser,
      icon: ch.icon,
      orderInLevel: ch.orderInLevel,
      questionCount: ch._count.questions,
      status: progressByChapter.get(ch.id)?.status ?? 'locked',
    }));
  }

  async findOne(userId: string, id: string) {
    const chapter = await this.prisma.chapter.findUnique({
      where: { id },
      include: { _count: { select: { questions: true } } },
    });
    if (!chapter) throw new NotFoundException('الفصل غير موجود.');

    const progress = await this.prisma.userProgress.findUnique({
      where: { userId_chapterId: { userId, chapterId: id } },
    });
    const answeredCount = progress ? ((progress.answeredQuestionIds as string[]) ?? []).length : 0;

    return {
      id: chapter.id,
      levelId: chapter.levelId,
      title: chapter.title,
      description: chapter.description,
      teaser: chapter.teaser,
      icon: chapter.icon,
      orderInLevel: chapter.orderInLevel,
      questionCount: chapter._count.questions,
      status: progress?.status ?? 'locked',
      answeredCount,
      completedAt: progress?.completedAt ?? null,
    };
  }
}
