ALTER TABLE gateway_identity_configuration_revisions
  ADD COLUMN IF NOT EXISTS security_event_issuer text,
  ADD COLUMN IF NOT EXISTS security_event_configuration_url text,
  ADD COLUMN IF NOT EXISTS security_event_audience text;

CREATE TABLE IF NOT EXISTS gateway_identity_onboarding_exchanges (
  id uuid PRIMARY KEY,
  revision_id uuid NOT NULL UNIQUE REFERENCES gateway_identity_configuration_revisions(id) ON DELETE CASCADE,
  remote_exchange_id uuid NOT NULL UNIQUE,
  exchange_token_ref text NOT NULL CHECK (exchange_token_ref ~ '^[a-z0-9][a-z0-9-]{0,127}$'),
  status text NOT NULL CHECK (status IN ('metadata_pending','preparing','ready','credentials_saved','completed','failed','expired')),
  remote_version bigint NOT NULL CHECK (remote_version > 0),
  expires_at timestamptz NOT NULL,
  version bigint NOT NULL DEFAULT 1 CHECK (version > 0),
  last_error_category text,
  auth_center_audit_id text,
  last_trace_id text,
  created_at timestamptz NOT NULL DEFAULT now(),
  updated_at timestamptz NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_gateway_identity_onboarding_status
  ON gateway_identity_onboarding_exchanges(status, updated_at DESC);
