-- webhook_deliveries: audit trail for every webhook delivery attempt.
-- A new row is inserted for each outbound event dispatch. Retries are tracked via
-- attempt_count and next_retry_at. Terminal states are 'delivered' and 'dead_letter'.
CREATE TABLE IF NOT EXISTS webhook_deliveries (
  id                UUID         PRIMARY KEY DEFAULT gen_random_uuid(),
  subscription_id   UUID         NOT NULL REFERENCES webhook_subscriptions(id) ON DELETE CASCADE,
  event_type        VARCHAR(128) NOT NULL,
  payload           JSONB        NOT NULL,                        -- full IWebhookPayload delivered
  status            VARCHAR(32)  NOT NULL DEFAULT 'pending',      -- 'pending' | 'delivered' | 'failed' | 'dead_letter'
  http_status_code  INTEGER,                                      -- populated after delivery attempt; NULL until first attempt
  attempt_count     INTEGER      NOT NULL DEFAULT 0,
  next_retry_at     TIMESTAMPTZ,                                  -- NULL until a failure sets a retry schedule
  delivered_at      TIMESTAMPTZ,                                  -- NULL until successful delivery
  created_at        TIMESTAMPTZ  NOT NULL DEFAULT NOW(),
  updated_at        TIMESTAMPTZ  NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_webhook_deliveries_subscription_id ON webhook_deliveries(subscription_id);
CREATE INDEX IF NOT EXISTS idx_webhook_deliveries_status ON webhook_deliveries(status);
CREATE INDEX IF NOT EXISTS idx_webhook_deliveries_next_retry_at ON webhook_deliveries(next_retry_at);
