import { revalidatePath } from "next/cache"
import { NextRequest } from "next/server"

async function handler(request: NextRequest) {
  const searchParams = request.nextUrl.searchParams
  const secret = searchParams.get("secret")
  const path = searchParams.get("path")

  // Validate the revalidation secret.
  if (secret !== process.env.DRUPAL_REVALIDATE_SECRET) {
    return new Response("Invalid secret.", { status: 401 })
  }

  if (!path) {
    return new Response("Missing path.", { status: 400 })
  }

  try {
    revalidatePath(path)
    return new Response(
      JSON.stringify({ revalidated: true, now: Date.now() }),
      {
        status: 200,
        headers: { "Content-Type": "application/json" },
      }
    )
  } catch (error) {
    return new Response(
      JSON.stringify({ message: "Error revalidating.", error }),
      { status: 500 }
    )
  }
}

export { handler as GET, handler as POST }
