import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { auth } from "@/lib/auth";
import { DEFAULT_VISUAL_CONFIG } from "@/lib/themeConfig";

export const dynamic = "force-dynamic";

export async function GET() {
  try {
    const setting = await prisma.siteSetting.findUnique({
      where: { key: "site_visual_theme" }
    });
    if (setting && setting.value) {
      try {
        const parsed = JSON.parse(setting.value);
        return NextResponse.json({ success: true, config: { ...DEFAULT_VISUAL_CONFIG, ...parsed } });
      } catch(e) {}
    }
    return NextResponse.json({ success: true, config: DEFAULT_VISUAL_CONFIG });
  } catch (error) {
    return NextResponse.json({ success: true, config: DEFAULT_VISUAL_CONFIG });
  }
}

export async function POST(req: Request) {
  try {
    const session = await auth();
    const role = (session?.user as any)?.role;
    if (!session || !["ADMIN", "SUPERADMIN", "MODERATOR", "EDITOR"].includes(role)) {
      return NextResponse.json({ error: "Non autorisé" }, { status: 401 });
    }

    const body = await req.json();
    const config = body?.config || body;

    const jsonVal = JSON.stringify(config);

    await prisma.siteSetting.upsert({
      where: { key: "site_visual_theme" },
      update: { value: jsonVal },
      create: { key: "site_visual_theme", value: jsonVal }
    });

    return NextResponse.json({ success: true, config });
  } catch (error: any) {
    console.error("Error saving theme config:", error);
    return NextResponse.json({ error: error.message || "Erreur serveur" }, { status: 500 });
  }
}
