import { timingSafeEqual } from "node:crypto";
import { revalidateTag } from "next/cache";
import { NextRequest, NextResponse } from "next/server";

import { CMS_CACHE_TAG } from "@/lib/revalidation";

function secretMatches(provided: string, expected: string): boolean {
  const a = Buffer.from(provided);
  const b = Buffer.from(expected);
  return a.length === b.length && timingSafeEqual(a, b);
}

export async function POST(req: NextRequest) {
  const secret = process.env.REVALIDATE_WEBHOOK_SECRET;
  if (!secret) {
    return NextResponse.json(
      { error: "revalidation is not configured" },
      { status: 503 }
    );
  }
  const provided = req.headers.get("x-revalidate-secret") ?? "";
  if (!secretMatches(provided, secret)) {
    return NextResponse.json({ error: "invalid secret" }, { status: 401 });
  }
  // expire: 0 purges immediately; the next request renders fresh
  revalidateTag(CMS_CACHE_TAG, { expire: 0 });
  return NextResponse.json({ revalidated: true, tag: CMS_CACHE_TAG });
}
