-- ASA Foundation: webhook_events table for Postgres inbox pattern
-- Stripe webhook events are stored here with status tracking.
-- A scheduled processor picks 'pending' events and processes them asynchronously.

CREATE TABLE IF NOT EXISTS public.webhook_events (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  stripe_event_id TEXT NOT NULL UNIQUE,
  type TEXT NOT NULL,
  payload JSONB NOT NULL DEFAULT '{}',
  status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'processing', 'processed', 'failed')),
  attempt_count INTEGER NOT NULL DEFAULT 0,
  locked_at TIMESTAMPTZ,
  last_error TEXT,
  received_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  processed_at TIMESTAMPTZ,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- Index for processor: find pending events efficiently
CREATE INDEX IF NOT EXISTS idx_webhook_events_status ON public.webhook_events (status) WHERE status = 'pending';

-- Index for deduplication lookup
CREATE INDEX IF NOT EXISTS idx_webhook_events_stripe_id ON public.webhook_events (stripe_event_id);

-- RLS: webhook_events should only be accessible by service_role (backend)
ALTER TABLE public.webhook_events ENABLE ROW LEVEL SECURITY;

-- No RLS policies = only service_role/admin can access (which is correct for webhooks)
