import { revalidateTag, revalidatePath } from "next/cache"
import { NextRequest, NextResponse } from "next/server"

export async function POST(req: NextRequest) {
  return handleRevalidate(req)
}

export async function GET(req: NextRequest) {
  return handleRevalidate(req)
}

async function handleRevalidate(req: NextRequest) {
  let body: Record<string, unknown> = {}
  try {
    body = await req.json()
  } catch {}

  const secret =
    req.nextUrl.searchParams.get("secret") || (body.secret as string)

  if (secret !== process.env.REVALIDATE_SECRET) {
    return NextResponse.json({ message: "Invalid secret" }, { status: 401 })
  }

  const tag =
    req.nextUrl.searchParams.get("tag") || (body.tag as string)

  const path =
    req.nextUrl.searchParams.get("path") || (body.path as string)

  if (!tag && !path) {
    return NextResponse.json(
      { message: "Missing 'tag' or 'path'" },
      { status: 400 }
    )
  }

  if (tag) {
    revalidateTag(tag)
  }

  if (path) {
    revalidatePath(path)
  }

  return NextResponse.json({
    revalidated: true,
    tag: tag || null,
    path: path || null,
    now: Date.now(),
  })
}
