import { PrismaService } from '../../infrastructure/database/prisma.service';

/**
 * Enrich result items with human-readable names resolved from IDs.
 * Adds userName, kbName, materialName fields where applicable.
 */
export async function enrichWithNames<T extends Record<string, any>>(
  prisma: PrismaService,
  items: T[],
): Promise<(T & { userName?: string; kbName?: string; materialName?: string })[]> {
  if (items.length === 0) return items;

  const userIds = [...new Set(items.map(i => i.userId).filter(Boolean))];
  const kbIds = [...new Set(items.map(i => i.knowledgeBaseId).filter(Boolean))];
  const materialIds = [...new Set(items.map(i => i.materialId).filter(Boolean))];

  const [users, kbs, materials] = await Promise.all([
    userIds.length > 0
      ? prisma.user.findMany({ where: { id: { in: userIds } }, select: { id: true, nickname: true, email: true } })
      : [],
    kbIds.length > 0
      ? prisma.knowledgeBase.findMany({ where: { id: { in: kbIds } }, select: { id: true, title: true } })
      : [],
    materialIds.length > 0
      ? prisma.knowledgeSource.findMany({ where: { id: { in: materialIds } }, select: { id: true, originalFilename: true, title: true } })
      : [],
  ]);

  const userMap = new Map<string, string>(users.map(u => [u.id, u.nickname || u.email || u.id] as [string, string]));
  const kbMap = new Map<string, string>(kbs.map(k => [k.id, k.title] as [string, string]));
  const matMap = new Map<string, string>(materials.map(m => [m.id, m.originalFilename || m.title || m.id] as [string, string]));

  return items.map(item => ({
    ...item,
    userName: userMap.get(item.userId),
    kbName: kbMap.get(item.knowledgeBaseId),
    materialName: matMap.get(item.materialId),
  }));
}
