import { NextRequest, NextResponse } from "next/server";
import { getDb } from "@/lib/mongodb";
import { getAllTemplates } from "@/lib/quiz-store";
import { createAttempt, getAttemptsByUserId } from "@/lib/user-store";
import { QuizAttempt, QuizMode, Question, AppSettings } from "@/types/quiz";

function shuffleArray<T>(array: T[]): T[] {
  const shuffled = [...array];
  for (let i = shuffled.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
  }
  return shuffled;
}

export async function POST(request: Request) {
  const body = await request.json();
  const { userId, quizMode } = body as { userId: string; quizMode: QuizMode };

  if (!userId) {
    return NextResponse.json({ error: "userId is required" }, { status: 400 });
  }

  const db = await getDb();
  const settingsDoc = await db.collection("settings").findOne({ _key: "app" });
  const settings: AppSettings = settingsDoc
    ? (settingsDoc as unknown as AppSettings)
    : { quizTheme: "classmaker" };

  const allTemplates = await getAllTemplates();
  const enabledIds = settings.userPathTemplateIds;
  const templates = enabledIds && enabledIds.length > 0
    ? allTemplates.filter((t) => enabledIds.includes(t.id))
    : allTemplates;
  const allQuestions: Question[] = templates.flatMap((t) => t.questions).filter((q) => !q.hidden);

  if (allQuestions.length === 0) {
    return NextResponse.json({ error: "No questions available" }, { status: 400 });
  }

  const shuffled = shuffleArray(allQuestions);
  const selected = shuffled.slice(0, Math.min(10, shuffled.length));

  const now = new Date().toISOString();
  const attempt: QuizAttempt = {
    id: `att-${Date.now()}-${Math.random().toString(36).substring(2, 7)}`,
    userId,
    source: "user",
    quizMode: quizMode || "testing",
    questions: selected,
    answers: selected.map((q) => ({ questionId: q.id, selectedAnswers: [] })),
    status: "in-progress",
    answeredCount: 0,
    totalQuestions: selected.length,
    correctCount: null,
    score: null,
    startedAt: now,
    completedAt: null,
    lastUpdatedAt: now,
  };

  await createAttempt(attempt);
  return NextResponse.json(attempt, { status: 201 });
}

export async function GET(request: NextRequest) {
  const userId = request.nextUrl.searchParams.get("userId");
  if (!userId) {
    return NextResponse.json({ error: "userId query param required" }, { status: 400 });
  }
  const attempts = await getAttemptsByUserId(userId);
  return NextResponse.json(attempts);
}
