import { NextRequest, NextResponse } from "next/server";
import { getSection, setSection, SECTION_KEYS } from "@/lib/db";
import { revalidatePath } from "next/cache";

type Params = { params: Promise<{ key: string }> };

export async function GET(_request: NextRequest, { params }: Params) {
  const { key } = await params;
  if (!SECTION_KEYS.includes(key as typeof SECTION_KEYS[number])) {
    return NextResponse.json({ error: "Invalid section key" }, { status: 400 });
  }

  const data = getSection(key);
  if (!data) {
    return NextResponse.json({ error: "Section not found" }, { status: 404 });
  }

  return NextResponse.json(data);
}

export async function PUT(request: NextRequest, { params }: Params) {
  const { key } = await params;
  if (!SECTION_KEYS.includes(key as typeof SECTION_KEYS[number])) {
    return NextResponse.json({ error: "Invalid section key" }, { status: 400 });
  }

  const data = await request.json();
  setSection(key, data);
  revalidatePath("/");

  return NextResponse.json({ ok: true });
}
