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

// Entered only via the `livePreview.url` link Payload puts in its admin
// (posts/legal-pages/testimonials, see payload.config.ts and those
// collections' own `admin.livePreview.url` resolvers) — enables Draft Mode
// so the target page renders its Live-Preview-aware components (see the
// `isPreview` checks in those pages' page.tsx), then redirects into the
// actual page. `path` is never redirected to as-is (open-redirect risk);
// it's validated to be an internal path first.
export async function GET(request: NextRequest) {
  const { searchParams } = request.nextUrl;
  const secret = searchParams.get("secret");
  const path = searchParams.get("path");

  if (!secret || secret !== process.env.PAYLOAD_PREVIEW_SECRET) {
    return new Response("Invalid secret", { status: 401 });
  }
  if (!path || !path.startsWith("/") || path.startsWith("//")) {
    return new Response("Invalid path", { status: 400 });
  }

  const draft = await draftMode();
  draft.enable();

  redirect(path);
}
