-- DocuSeal webhook event log.
--
-- Append-only audit trail of every event delivered by DocuSeal to
-- /api/docuseal/webhook/<token>. The full webhook body is preserved as
-- jsonb in `payload` so we never lose information; the extracted columns
-- are for fast lookup and downstream notification logic.
--
-- RLS is on with no policies; only the service-role key (used by the
-- webhook receiver in main.el) can read or write.

create table if not exists public.docuseal_events (
  id bigserial primary key,
  event_type text not null,
  received_at timestamptz not null default now(),
  event_timestamp timestamptz,
  submission_id bigint,
  signer_email text,
  signer_name text,
  payload jsonb not null,
  ua text,
  ip text
);

create index if not exists docuseal_events_submission_id_idx on public.docuseal_events (submission_id);
create index if not exists docuseal_events_email_idx on public.docuseal_events (signer_email);
create index if not exists docuseal_events_event_type_idx on public.docuseal_events (event_type);
create index if not exists docuseal_events_received_at_idx on public.docuseal_events (received_at desc);

alter table public.docuseal_events enable row level security;
