// Draft Mode API Route
//
// Enables Next.js draft mode so that pages can fetch unpublished
// Payload CMS content. This route is called by Payload's live preview
// iframe (configured in each collection's admin.livePreview.url) to
// set the draft mode cookie before redirecting to the actual page.
//
// Only authenticated Payload users can activate draft mode, ensuring
// public visitors never see draft content.
//
// See: https://nextjs.org/docs/app/guides/draft-mode

import { draftMode } from 'next/headers'
import { redirect } from 'next/navigation'
import { getPayload } from 'payload'
import config from '@/payload.config'
import { headers } from 'next/headers'

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url)
  const url = searchParams.get('url')

  if (!url) {
    return new Response('Missing url parameter', { status: 400 })
  }

  // Verify the request comes from an authenticated Payload CMS user
  const payload = await getPayload({ config })
  const allHeaders = await headers()
  const { user } = await payload.auth({ headers: allHeaders })

  if (!user) {
    return new Response('Unauthorized', { status: 401 })
  }

  // Enable draft mode cookie — subsequent page renders will see
  // draftMode().isEnabled === true and can fetch draft content
  const draft = await draftMode()
  draft.enable()

  redirect(url)
}
