import { revalidateTag } from "next/cache";

import { webhookSecret } from "@/sanity/env";

/**
 * Sanity-triggered revalidation webhook.
 *
 * Expected payload (configured on the Sanity webhook as a GROQ projection):
 *   { "_type": string, "slug": string }
 *
 * The caller must send the shared secret in the `x-webhook-secret` header.
 * On success we invalidate two tags:
 *   - `${_type}`              → refreshes list queries
 *   - `${_type}:${slug}`      → refreshes the specific detail page
 *
 * If the webhook secret env is missing the endpoint returns 503 so the
 * operator notices during setup rather than silently accepting all traffic.
 */
export async function POST(request: Request) {
  if (!webhookSecret) {
    return Response.json(
      { error: "webhook secret not configured" },
      { status: 503 },
    );
  }

  const provided = request.headers.get("x-webhook-secret");
  if (provided !== webhookSecret) {
    return Response.json({ error: "unauthorized" }, { status: 401 });
  }

  let body: { _type?: string; slug?: string };
  try {
    body = (await request.json()) as { _type?: string; slug?: string };
  } catch {
    return Response.json({ error: "invalid json body" }, { status: 400 });
  }

  const type = typeof body._type === "string" ? body._type : "";
  const slug = typeof body.slug === "string" ? body.slug : "";
  if (!type) {
    return Response.json(
      { error: "missing _type in payload" },
      { status: 400 },
    );
  }

  const tags: string[] = [type];
  try {
    // Next 16 requires the cache life profile as the second argument.
    // "max" gives us stale-while-revalidate semantics which is what we
    // want for editorial content — readers keep seeing the stale post
    // while the fresh one is refetched in the background.
    revalidateTag(type, "max");
    if (slug) {
      const detailTag = `${type}:${slug}`;
      revalidateTag(detailTag, "max");
      tags.push(detailTag);
    }
  } catch (error) {
    return Response.json(
      {
        error: "revalidation failed",
        detail: error instanceof Error ? error.message : String(error),
      },
      { status: 500 },
    );
  }

  return Response.json({ revalidated: true, tags });
}
