import { NextResponse } from "next/server";
import { getDb } from "@/lib/mongodb";
import { AppSettings } from "@/types/quiz";

const DEFAULT_SETTINGS: AppSettings = { quizTheme: "classmaker" };

async function getSettings(): Promise<AppSettings> {
  const db = await getDb();
  const doc = await db.collection("settings").findOne({ _key: "app" });
  if (!doc) return { ...DEFAULT_SETTINGS };
  const { _id, _key, ...settings } = doc;
  void _id;
  void _key;
  return settings as unknown as AppSettings;
}

export async function GET() {
  return NextResponse.json(await getSettings());
}

export async function PUT(request: Request) {
  const body = await request.json();
  const db = await getDb();

  const update: Record<string, unknown> = {};
  if (body.quizTheme === "classmaker" || body.quizTheme === "modern") {
    update.quizTheme = body.quizTheme;
  }
  if (Array.isArray(body.userPathTemplateIds)) {
    update.userPathTemplateIds = body.userPathTemplateIds;
  }

  await db.collection("settings").updateOne(
    { _key: "app" },
    { $set: update },
    { upsert: true }
  );

  return NextResponse.json(await getSettings());
}
