/** GET /api/users/search?q=... — Nickname-Suche für neue DM-Gespräche */
export default defineEventHandler(async (event) => {
  const user = await requireUser(event);
  const query = getQuery(event);
  const q = ((query.q as string) ?? "").trim();

  if (!q || q.length < 2) return [];

  const db = usePrisma();

  const results = await db.profile.findMany({
    where: {
      id: { not: user.id },
      deletedAt: null,
      OR: [
        { nickname: { contains: q, mode: "insensitive" } },
        { username: { contains: q, mode: "insensitive" } },
      ],
    },
    select: { id: true, nickname: true, username: true, avatar: true },
    take: 20,
    orderBy: { nickname: "asc" },
  });

  return results.map((p) => ({
    id: p.id,
    nickname: p.nickname ?? p.username ?? "Anonym",
    avatar: p.avatar ?? null,
  }));
});
