// Sanity Function: Publish webhook handler
// Demonstrates: defineFunction, document publish trigger, event handling, external API calls

import { defineFunction } from "sanity/functions"

// Define a function that triggers when a document is published
export const onPublishWebhook = defineFunction({
  name: "on-publish-webhook",
  title: "Publish Webhook",
  description: "Sends a webhook notification when a document is published",

  // Trigger on document publish events
  trigger: {
    type: "document.publish",
    // Optionally filter by document type
    filter: {
      types: ["post", "article"],
    },
  },

  // The handler function receives the event context
  async handler(event, context) {
    const { document, previousDocument } = event
    const { projectId, dataset } = context

    // Build the webhook payload
    const payload = {
      event: "document.published",
      projectId,
      dataset,
      documentId: document._id,
      documentType: document._type,
      title: document.title ?? document._id,
      publishedAt: new Date().toISOString(),
      isUpdate: !!previousDocument,
    }

    // Send to an external webhook URL (configured via environment/secrets)
    const webhookUrl = process.env.WEBHOOK_URL
    if (!webhookUrl) {
      console.warn("WEBHOOK_URL not configured, skipping notification")
      return { success: false, reason: "no webhook URL configured" }
    }

    const response = await fetch(webhookUrl, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(payload),
    })

    if (!response.ok) {
      console.error(`Webhook failed: ${response.status} ${response.statusText}`)
      return { success: false, status: response.status }
    }

    return { success: true, documentId: document._id }
  },
})
