import { type NextRequest } from "next/server";
import { prisma } from "@/lib/db";
import { requireAuth } from "@/lib/auth";

export async function GET() {
  try {
    await requireAuth();
    const settings = await prisma.siteSettings.findUnique({ where: { id: "main" } });
    return Response.json(settings ?? {});
  } catch {
    return Response.json({ error: "Unauthorized" }, { status: 401 });
  }
}

export async function PUT(req: NextRequest) {
  try {
    await requireAuth();
    const body = await req.json();
    const { id, updatedAt, ...data } = body;
    const settings = await prisma.siteSettings.upsert({
      where: { id: "main" },
      create: { id: "main", siteTitle: "Ali Taghavi", ...data },
      update: data,
    });
    return Response.json(settings);
  } catch (err) {
    console.error("[settings/PUT]", err);
    return Response.json({ error: "Server error" }, { status: 500 });
  }
}
