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

// Next.js 16 requires a cache profile argument for revalidateTag.
// "max" lifecycle = invalidate all entries with this tag immediately.
const PROFILE = "max" as const;

/**
 * Webhook endpoint for WordPress to ping when content changes.
 *
 * Security: requires a shared secret in the `Authorization: Bearer <token>` header
 * matching env REVALIDATE_TOKEN.
 *
 * Payload:
 *   { type: "post" | "category" | "tag" | "all", slug?: string }
 *
 * Configure in WordPress (e.g. WP Webhooks plugin) to POST on save_post / category_edit / etc.
 */
export const dynamic = "force-dynamic";

export async function POST(req: Request) {
  const token = process.env.REVALIDATE_TOKEN;
  const auth = req.headers.get("authorization") ?? "";
  if (!token || auth !== `Bearer ${token}`) {
    return NextResponse.json({ ok: false, error: "Unauthorized" }, { status: 401 });
  }

  let body: { type?: string; slug?: string };
  try {
    body = await req.json();
  } catch {
    return NextResponse.json({ ok: false, error: "Invalid JSON" }, { status: 400 });
  }

  const type = body.type ?? "all";
  const slug = body.slug;

  try {
    if (type === "post" && slug) {
      revalidatePath(`/${slug}`);
      revalidateTag(`post:${slug}`, PROFILE);
      // Homepage + first category page might also show this post
      revalidatePath("/");
    } else if (type === "category") {
      if (slug) revalidatePath(`/category/${slug}`);
      revalidateTag("categories", PROFILE);
      revalidatePath("/");
    } else if (type === "tag") {
      if (slug) revalidatePath(`/tag/${slug}`);
      revalidateTag("tags", PROFILE);
    } else {
      // type === "all"
      revalidatePath("/", "layout");
      revalidateTag("categories", PROFILE);
      revalidateTag("tags", PROFILE);
    }
    return NextResponse.json({ ok: true, type, slug });
  } catch (e) {
    return NextResponse.json(
      { ok: false, error: e instanceof Error ? e.message : String(e) },
      { status: 500 }
    );
  }
}

export async function GET() {
  return NextResponse.json({ ok: true, hint: "POST with Authorization: Bearer <token> + JSON body" });
}
