create table if not exists public.billing_webhook_events ( id uuid primary key default gen_random_uuid(), provider text not null check (provider in ('stripe')), external_event_id text not null, event_type text not null, status text not null check (status in ('received', 'processed', 'failed', 'ignored')) default 'received', workspace_id uuid references public.workspaces (id) on delete set null, external_customer_ref text, external_subscription_ref text, payload_json jsonb not null, error_message text, received_at timestamptz not null default now(), processed_at timestamptz, created_at timestamptz not null default now(), updated_at timestamptz not null default now(), constraint billing_webhook_events_provider_event_key unique (provider, external_event_id) ); create index if not exists billing_webhook_events_status_idx on public.billing_webhook_events (status); create index if not exists billing_webhook_events_workspace_id_idx on public.billing_webhook_events (workspace_id); create index if not exists billing_webhook_events_customer_ref_idx on public.billing_webhook_events (external_customer_ref); create index if not exists billing_webhook_events_subscription_ref_idx on public.billing_webhook_events (external_subscription_ref); drop trigger if exists set_billing_webhook_events_updated_at on public.billing_webhook_events; create trigger set_billing_webhook_events_updated_at before update on public.billing_webhook_events for each row execute function public.set_updated_at();