// src/next/revalidate.ts
import { revalidateTag, revalidatePath } from "next/cache";

// src/webhooks/verify.ts
import crypto from "crypto";
import { z } from "zod";
var WebhookEventSchema = z.enum([
  "page.published",
  "entry.published",
  "navigation.updated",
  "theme.updated",
  "site.settings_updated"
]);
var PagePublishedDataSchema = z.object({
  pageId: z.string(),
  path: z.string(),
  slug: z.string().optional()
});
var EntryPublishedDataSchema = z.object({
  entryId: z.string(),
  path: z.string(),
  contentType: z.string()
});
var NavigationUpdatedDataSchema = z.object({
  menuId: z.string().optional()
});
var EmptyDataSchema = z.object({});
var WebhookDataSchema = z.union([
  PagePublishedDataSchema,
  EntryPublishedDataSchema,
  NavigationUpdatedDataSchema,
  EmptyDataSchema
]);
var WebhookPayloadSchema = z.object({
  /** Event type */
  event: WebhookEventSchema,
  /** ISO timestamp of when the event occurred */
  timestamp: z.string(),
  /** Site ID that triggered the event */
  siteId: z.string(),
  /** Event-specific data (shape depends on event type) */
  data: z.record(z.string(), z.unknown()),
  /** Cache invalidation tags (for tag-based revalidation) */
  tags: z.array(z.string()).optional()
});
function verifyWebhookSignature(payload, signature, secret) {
  const expectedSignature = crypto.createHmac("sha256", secret).update(payload).digest("hex");
  if (signature.length !== expectedSignature.length) {
    return false;
  }
  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(expectedSignature)
  );
}
function parseWebhookPayload(body) {
  let parsed;
  try {
    parsed = JSON.parse(body);
  } catch {
    return { success: false, error: "Invalid JSON" };
  }
  const result = WebhookPayloadSchema.safeParse(parsed);
  if (!result.success) {
    return { success: false, error: `Invalid payload: ${result.error.message}` };
  }
  return { success: true, payload: result.data };
}

// src/next/revalidate.ts
function createRevalidateHandler(options = {}) {
  return async function handleRevalidateRequest(request) {
    const secret = options.secret ?? process.env.RIVERBANK_WEBHOOK_SECRET;
    if (!secret) {
      console.error("[Riverbank] RIVERBANK_WEBHOOK_SECRET not configured");
      return Response.json(
        { error: "Webhook secret not configured" },
        { status: 500 }
      );
    }
    const body = await request.text();
    const signature = request.headers.get("x-riverbank-signature");
    if (!signature || !verifyWebhookSignature(body, signature, secret)) {
      return Response.json({ error: "Invalid signature" }, { status: 401 });
    }
    const parseResult = parseWebhookPayload(body);
    if (!parseResult.success) {
      return Response.json({ error: parseResult.error }, { status: 400 });
    }
    const payload = parseResult.payload;
    const revalidated = [];
    if (payload.tags?.length) {
      for (const tag of payload.tags) {
        revalidateTag(tag, "max");
        revalidated.push(`tag:${tag}`);
      }
    }
    const path = typeof payload.data?.path === "string" ? payload.data.path : void 0;
    if (path) {
      revalidatePath(path);
      revalidated.push(`path:${path}`);
    }
    if (revalidated.length > 0) {
      console.log(
        `[Riverbank] Revalidated: ${revalidated.join(", ")} (event: ${payload.event})`
      );
    }
    if (options.onRevalidate) {
      options.onRevalidate(payload, revalidated);
    }
    return Response.json({
      revalidated: true,
      items: revalidated,
      event: payload.event,
      timestamp: Date.now()
    });
  };
}
export {
  createRevalidateHandler
};
