CREATE TABLE IF NOT EXISTS gateway_security_event_connections (
  connection_id uuid PRIMARY KEY,
  singleton boolean NOT NULL DEFAULT true UNIQUE CHECK (singleton),
  transmitter_issuer text NOT NULL,
  endpoint_url text NOT NULL,
  audience text,
  stream_id uuid,
  credential_ref text NOT NULL,
  next_credential_ref text,
  lifecycle_status text NOT NULL,
  version bigint NOT NULL DEFAULT 1,
  last_error_category text,
  idempotency_key text NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now(),
  updated_at timestamptz NOT NULL DEFAULT now(),
  CONSTRAINT gateway_security_event_connection_status CHECK (lifecycle_status IN (
    'connecting','verifying','bootstrap','enabled','degraded','rotating',
    'disconnect_pending','retiring','error'
  )),
  CONSTRAINT gateway_security_event_connection_stream_pair CHECK (
    (audience IS NULL AND stream_id IS NULL) OR (audience IS NOT NULL AND stream_id IS NOT NULL)
  )
);

CREATE UNIQUE INDEX IF NOT EXISTS idx_gateway_security_event_connections_idempotency
  ON gateway_security_event_connections(idempotency_key);

CREATE TABLE IF NOT EXISTS gateway_security_event_connection_idempotency (
  operation text NOT NULL,
  idempotency_key text NOT NULL,
  request_hash text NOT NULL,
  response jsonb NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (operation, idempotency_key),
  CONSTRAINT gateway_security_event_connection_idempotency_operation
    CHECK (operation IN ('connect','verify','rotate','disconnect'))
);

CREATE INDEX IF NOT EXISTS idx_gateway_security_event_connection_idempotency_created
  ON gateway_security_event_connection_idempotency(created_at);
