// 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 };
}
export {
  WebhookPayloadSchema,
  parseWebhookPayload,
  verifyWebhookSignature
};
