// Revalidation on-demand déclenchée par WordPress (webhook save_post → POST ici).
// Auth : header `x-revalidate-secret` (POST) ou ?secret= (GET de test manuel).

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

interface RevalidateBody {
  tags?: string[];
  paths?: string[];
}

function unauthorized() {
  return NextResponse.json({ revalidated: false, error: "Invalid secret" }, { status: 401 });
}

function isAuthorized(secret: string | null): boolean {
  const expected = process.env.REVALIDATE_SECRET;
  return Boolean(expected) && secret === expected;
}

export async function POST(request: NextRequest) {
  if (!isAuthorized(request.headers.get("x-revalidate-secret"))) {
    return unauthorized();
  }

  let body: RevalidateBody = {};
  try {
    body = (await request.json()) as RevalidateBody;
  } catch {
    return NextResponse.json(
      { revalidated: false, error: "Body JSON invalide (attendu { tags?: string[], paths?: string[] })" },
      { status: 400 }
    );
  }

  const tags = Array.isArray(body.tags) ? body.tags.filter(Boolean) : [];
  const paths = Array.isArray(body.paths) ? body.paths.filter(Boolean) : [];

  // Next 16 : le profil "max" correspond aux entrées cachées sans expiration
  // (revalidate: false côté fetchGraphQL) — purge complète du tag.
  for (const tag of tags) revalidateTag(tag, "max");
  for (const path of paths) revalidatePath(path);

  return NextResponse.json({ revalidated: true, tags, paths, now: Date.now() });
}

// Test manuel : GET /api/revalidate?secret=xxx&tag=page&path=/contact
export async function GET(request: NextRequest) {
  const { searchParams } = request.nextUrl;
  if (!isAuthorized(searchParams.get("secret"))) {
    return unauthorized();
  }

  const tags = searchParams.getAll("tag").filter(Boolean);
  const paths = searchParams.getAll("path").filter(Boolean);

  for (const tag of tags) revalidateTag(tag, "max");
  for (const path of paths) revalidatePath(path);

  return NextResponse.json({ revalidated: true, tags, paths, now: Date.now() });
}
