import { listRooms, seedDefaultRooms } from "../../../db/chat-rooms";
import { getUsersMeta } from "../../../utils/getUsersMeta";

/** GET /api/chat/rooms – Alle Rooms (public + eigene) */
export default defineEventHandler(async (event) => {
  const user = await requireUser(event);

  // Auto-seed default groups on first request
  await seedDefaultRooms().catch(() => {});

  const rooms = await listRooms(user.id);

  // Resolve user meta for last message senders
  const senderIds = rooms
    .map((r) => r.messages[0]?.userId)
    .filter(Boolean) as string[];
  const meta = senderIds.length > 0 ? await getUsersMeta(senderIds) : {};

  return rooms.map((r) => {
    const lastMsg = r.messages[0];
    const isMember = r.members.some((m) => m.userId === user.id);
    const myRole = r.members.find((m) => m.userId === user.id)?.role ?? null;
    return {
      id: r.id,
      name: r.name,
      description: r.description,
      isPublic: r.isPublic,
      isDefault: r.isDefault,
      joinMode: r.joinMode,
      avatarUrl: r.avatarUrl ?? null,
      inviteCode:
        myRole === "owner" || myRole === "admin" ? r.inviteCode : null,
      memberCount: r.memberCount,
      isMember,
      myRole,
      createdBy: r.createdBy,
      lastMessage: lastMsg
        ? {
            content: lastMsg.content.slice(0, 80),
            createdAt: lastMsg.createdAt,
            senderName: meta[lastMsg.userId]?.nickname ?? "Anonym",
          }
        : null,
    };
  });
});
