import { cookies, draftMode } from "next/headers";
import { redirect } from "next/navigation";
import { NextRequest } from "next/server";

// Wagtail-headless-preview directs the editor's preview iframe here with
// ?content_type=app.Model&token=<signed>. We stash the token in a cookie,
// enable Next.js draft mode, and redirect to the type-dispatching renderer.
export async function GET(req: NextRequest) {
  const token = req.nextUrl.searchParams.get("token");
  const contentType = req.nextUrl.searchParams.get("content_type");
  if (!token || !contentType) {
    return new Response("missing token/content_type", { status: 400 });
  }

  (await draftMode()).enable();
  (await cookies()).set("preview-token", token, {
    httpOnly: true,
    sameSite: "lax",
    secure: process.env.NODE_ENV === "production",
    maxAge: 60 * 60 * 24,
    path: "/",
  });

  redirect("/preview/render");
}
