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

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

  async findAll(category?: string, search?: string) {
    const terms = await this.prisma.term.findMany({
      where: {
        category: category || undefined,
        termName: search ? { contains: search, mode: 'insensitive' } : undefined,
      },
      orderBy: { order: 'asc' },
    });
    return terms;
  }

  async findOne(id: string) {
    const term = await this.prisma.term.findUnique({
      where: { id },
      include: {
        relatedFrom: { include: { relatedTerm: true } },
        chapterLinks: { include: { chapter: true } },
      },
    });
    if (!term) throw new NotFoundException('المصطلح غير موجود.');

    return {
      id: term.id,
      termName: term.termName,
      explanation: term.explanation,
      category: term.category,
      icon: term.icon,
      relatedTerms: term.relatedFrom.map((r) => ({ id: r.relatedTerm.id, termName: r.relatedTerm.termName })),
      relatedChapters: term.chapterLinks.map((l) => ({ id: l.chapter.id, title: l.chapter.title })),
    };
  }

  async categories() {
    const rows = await this.prisma.term.findMany({ select: { category: true }, distinct: ['category'] });
    return rows.map((r) => r.category);
  }
}
