import { NextResponse } from "next/server";
import { getAllTemplates, saveTemplate } from "@/lib/quiz-store";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { QuizTemplate } from "@/types/quiz";

export async function GET() {
  const templates = await getAllTemplates();
  return NextResponse.json(templates);
}

export async function POST(request: Request) {
  const session = await getServerSession(authOptions);
  if (!session || (session.user as { role?: string }).role !== "admin") {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const body: QuizTemplate = await request.json();
  await saveTemplate(body);
  return NextResponse.json(body, { status: 201 });
}
