import { NextResponse } from "next/server";
import { requireAdminSession } from "@/lib/admin/auth";
import { getAllContent, saveContent } from "@/lib/content/service";
import type { ContentDocuments, ContentKey } from "@/lib/content/types";

const keys: ContentKey[] = ["home", "services", "radio-service", "repair", "about", "contact", "settings"];

function isContentKey(value: unknown): value is ContentKey {
  return typeof value === "string" && keys.includes(value as ContentKey);
}

export async function GET() {
  if (!await requireAdminSession()) return NextResponse.json({ message: "Nicht autorisiert." }, { status: 401 });
  return NextResponse.json({ content: await getAllContent() });
}

export async function PUT(request: Request) {
  if (!await requireAdminSession()) return NextResponse.json({ message: "Nicht autorisiert." }, { status: 401 });

  const body = await request.json() as { key?: unknown; content?: unknown };
  if (!isContentKey(body.key) || !body.content) {
    return NextResponse.json({ message: "Ungültige Content-Anfrage." }, { status: 400 });
  }

  const saved = await saveContent(body.key, body.content as ContentDocuments[typeof body.key]);
  return NextResponse.json({ message: "Inhalt gespeichert.", key: body.key, content: saved });
}
