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

import { previewSecret } from "@/sanity/env";

/**
 * GET /api/preview?secret=...&slug=/news/my-post
 *
 * Enables Next.js `draftMode()` so RSC fetches can select the `drafts` Sanity
 * perspective and render unpublished content. The `secret` query param must
 * match `NEXT_PUBLIC_SANITY_PREVIEW_SECRET`, otherwise we 401.
 *
 * If the env is not configured at all we return 503 so Studio falls back
 * gracefully instead of silently enabling preview with no secret.
 */
export async function GET(request: NextRequest) {
  if (!previewSecret) {
    return NextResponse.json(
      { error: "preview not configured" },
      { status: 503 },
    );
  }
  const secret = request.nextUrl.searchParams.get("secret");
  const slug = request.nextUrl.searchParams.get("slug") || "/";

  if (secret !== previewSecret) {
    return NextResponse.json({ error: "invalid secret" }, { status: 401 });
  }

  const draft = await draftMode();
  draft.enable();
  redirect(slug);
}
