import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { BentoDashboard } from "@/components/dashboard/BentoDashboard";
import type { Metadata } from "next";

export const metadata: Metadata = {
  title: "Dashboard | QuizB",
};

async function getUserStats(userId: string) {
  const [user, recentResults, totalResults] = await Promise.all([
    prisma.user.findUnique({
      where: { id: userId },
      select: {
        name: true, image: true, level: true, xp: true,
        streak: true, totalScore: true, quizzesPlayed: true,
      },
    }),
    prisma.result.findMany({
      where: { userId },
      orderBy: { createdAt: "desc" },
      take: 5,
      include: {
        quiz: {
          select: {
            title: true, slug: true,
            category: { select: { name: true, icon: true } },
          },
        },
      },
    }),
    prisma.result.count({ where: { userId } }),
  ]);

  const avgScore = recentResults.length
    ? Math.round(recentResults.reduce((sum, r) => sum + r.percentage, 0) / recentResults.length)
    : 0;

  return { user, recentResults, totalResults, avgScore };
}

export default async function DashboardPage() {
  const session = await getServerSession(authOptions);
  if (!session?.user?.id) return null;

  const stats = await getUserStats(session.user.id);

  return (
    <div className="min-h-screen bg-background">
      <div className="container mx-auto px-4 py-8 max-w-6xl">
        <BentoDashboard stats={stats} user={session.user} />
      </div>
    </div>
  );
}
