import { requireAuth } from "@/lib/session";
import { db } from "@/lib/db";
import DailyQuizClient from "./DailyQuizClient";

export default async function QuizPage() {
  const session = await requireAuth();
  const userId = (session.user as any).id;

  const now = new Date();
  const todayStart = new Date(now);
  todayStart.setHours(0, 0, 0, 0);
  const todayEnd = new Date(now);
  todayEnd.setHours(23, 59, 59, 999);

  const quiz = await db.dailyQuiz.findFirst({
    where: { date: { gte: todayStart, lte: todayEnd } },
    include: {
      questions: {
        orderBy: { order: "asc" },
        select: { id: true, questionText: true, options: true, order: true },
      },
    },
  });

  const alreadySubmitted = quiz
    ? !!(await db.quizSubmission.findUnique({
        where: { userId_quizId: { userId, quizId: quiz.id } },
      }))
    : false;

  return (
    <div className="min-h-screen bg-gray-950 text-white py-10 px-4">
      <DailyQuizClient quiz={quiz} alreadySubmitted={alreadySubmitted} />
    </div>
  );
}
