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

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 });
  }

  let data = getSection(key);
  if (!data) {
    // Auto-seed from fallback content if section doesn't exist yet
    const fallback = (siteContent as unknown as Record<string, unknown>)[key];
    if (fallback) {
      setSection(key, fallback);
      data = fallback;
    } else {
      return NextResponse.json({ error: "Section not found" }, { status: 404 });
    }
  }

  return NextResponse.json(data, {
    headers: { "Cache-Control": "private, max-age=60" },
  });
}

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);
  invalidateContentCache();
  revalidatePath("/");

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