// INCOMING webhook — a public endpoint a partner POSTs to. Mounts at
// `/webhooks/orders` (the `id`). The framework's incoming middleware runs
// BEFORE your handler:
//
//   1. verifies the `X-Webhook-Signature: t=<ts>,v1=<hmac>` HMAC over
//      `<ts>.<rawBody>` with VOLTRO_WEBHOOK_SECRET_ORDERS  → 401 on mismatch
//   2. rejects a `t` older than the replay window                → 401
//   3. decodes the body against `payload`                        → 422 on bad shape
//   4. claims the `Idempotency-Key` (dedup)            → 200 {duplicate:true} on replay
//
// Only a request that passes ALL of that reaches `handler`. That's the whole
// point: you never hand-roll signature checks, and forged traffic never runs
// your code.

import { defineIncomingWebhook } from '@voltro/plugin-webhooks'
import { genericProvider } from '@voltro/plugin-webhooks/providers'
import { Schema } from 'effect'

export default defineIncomingWebhook({
  id:       'orders',
  provider: genericProvider(),   // HMAC `<ts>.<body>` → X-Webhook-Signature; idempotency via Idempotency-Key
  payload:  Schema.Struct({
    event:    Schema.String,
    orderId:  Schema.String,
    sku:      Schema.String,
    totalCents: Schema.Number,
  }),
  // ctx.body is validated; ctx.idempotencyKey + ctx.headers are also available.
  // No ctx.store here — a webhook handler is app glue; for DB writes, enqueue a
  // workflow or call your own service. We log to prove receipt (the dev console
  // bridge surfaces it in the terminal).
  handler: async (ctx) => {
    console.log(`[webhook:orders] verified ${ctx.body.event} for ${ctx.body.orderId} (idempotency=${ctx.idempotencyKey})`)
  },
})
