import { prisma } from "./prisma";
import { getAppSettings } from "./settings";
import { getCurrentUser, userIsAdmin } from "./session";

type CurrentUser = NonNullable<Awaited<ReturnType<typeof getCurrentUser>>>;

export async function getShellContext(user: CurrentUser) {
  const [rooms, pendingRequests, activeRoomCount, settings] = await Promise.all([
    prisma.room.findMany({
      where: {
        OR: [{ ownerId: user.id }, { members: { some: { userId: user.id } } }, { visibility: "PUBLIC" }]
      },
      include: { _count: { select: { members: true, mediaSources: true } } },
      orderBy: [{ ownerId: "desc" }, { updatedAt: "desc" }],
      take: 8
    }),
    prisma.friendship.count({ where: { receiverId: user.id, status: "PENDING" } }),
    prisma.room.count({ where: { mediaSources: { some: {} } } }),
    getAppSettings()
  ]);

  return {
    isAdmin: userIsAdmin(user),
    userName: user.displayName || user.username,
    userAvatarUrl: user.avatarUrl,
    instanceName: settings.instanceName,
    pendingRequests,
    activeRoomCount,
    rooms: rooms.map((room) => ({
      id: room.id,
      name: room.name,
      slug: room.slug,
      href: `/rooms/${encodeURIComponent(room.slug)}`,
      visibility: room.visibility,
      participantCount: room._count.members + 1,
      queueCount: room._count.mediaSources,
      isPersonal: room.ownerId === user.id
    }))
  };
}
