// ============================================================================
// Webhook event catalog.
//
// The single source of truth for the outbound-webhook / Zapier integration.
// Every event a landlord can subscribe to is declared here. `emitWebhookEvent`
// (see ./emit) fans an event out to all of an account's endpoints that either
// subscribe to the event id or subscribe to everything (empty `events` array).
//
// This module is intentionally dependency-free (no `crypto`, no db) so it can be
// imported from client components (e.g. the settings form) and shared schemas.
// ============================================================================

export const WEBHOOK_EVENTS = [
  {
    id: "property.created",
    label: "Property created",
    description: "A property was added to the portfolio.",
  },
  {
    id: "tenant.created",
    label: "Tenant created",
    description: "A new tenant was added.",
  },
  {
    id: "maintenance.created",
    label: "Maintenance request opened",
    description: "A maintenance request was submitted (dashboard, API, or tenant portal).",
  },
  {
    id: "maintenance.updated",
    label: "Maintenance status changed",
    description: "A maintenance request moved to a new status (e.g. resolved).",
  },
  {
    id: "payment.recorded",
    label: "Payment recorded",
    description: "A rent payment record was created.",
  },
  {
    id: "payment.paid",
    label: "Payment marked paid",
    description: "A rent payment was marked as paid.",
  },
  {
    id: "lease.created",
    label: "Lease created",
    description: "A lease was created for a tenant.",
  },
] as const

export type WebhookEvent = (typeof WEBHOOK_EVENTS)[number]["id"]

/** All valid event ids, plus the reserved `ping` used by the "Send test" button. */
export const WEBHOOK_EVENT_IDS = WEBHOOK_EVENTS.map((e) => e.id) as WebhookEvent[]

export const PING_EVENT = "ping" as const

export function isWebhookEvent(value: unknown): value is WebhookEvent {
  return typeof value === "string" && WEBHOOK_EVENT_IDS.includes(value as WebhookEvent)
}

/** The JSON envelope every webhook POST body uses. */
export type WebhookEnvelope = {
  id: string
  event: WebhookEvent | typeof PING_EVENT
  created_at: string
  data: Record<string, unknown>
}
