CREATE TABLE IF NOT EXISTS gateway_identity_configuration_revisions (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  state text NOT NULL DEFAULT 'draft' CHECK (state IN ('draft','validated','active','superseded','failed')),
  schema_version integer NOT NULL DEFAULT 1 CHECK (schema_version = 1),
  auth_center_url text NOT NULL,
  issuer text,
  tenant_id text,
  application_id text,
  audience text,
  browser_client_id text,
  machine_client_id text,
  scopes jsonb NOT NULL DEFAULT '[]'::jsonb CHECK (jsonb_typeof(scopes) = 'array'),
  capabilities jsonb NOT NULL DEFAULT '[]'::jsonb CHECK (jsonb_typeof(capabilities) = 'array'),
  role_prefix text NOT NULL DEFAULT 'gateway.',
  local_tenant_key text NOT NULL,
  public_base_url text NOT NULL,
  web_base_url text NOT NULL,
  jit_enabled boolean NOT NULL DEFAULT true,
  legacy_jwt_enabled boolean NOT NULL DEFAULT false,
  token_introspection boolean NOT NULL DEFAULT false,
  session_revocation boolean NOT NULL DEFAULT false,
  machine_credential_ref text,
  session_encryption_key_ref text,
  session_idle_seconds integer NOT NULL DEFAULT 1800 CHECK (session_idle_seconds > 0),
  session_absolute_seconds integer NOT NULL DEFAULT 28800 CHECK (session_absolute_seconds > session_idle_seconds),
  session_refresh_seconds integer NOT NULL DEFAULT 60 CHECK (session_refresh_seconds > 0 AND session_refresh_seconds < session_idle_seconds),
  version bigint NOT NULL DEFAULT 1 CHECK (version > 0),
  last_error_category text,
  last_trace_id text,
  last_audit_id text,
  validated_at timestamptz,
  activated_at timestamptz,
  superseded_at timestamptz,
  created_at timestamptz NOT NULL DEFAULT now(),
  updated_at timestamptz NOT NULL DEFAULT now(),
  CHECK (machine_credential_ref IS NULL OR machine_credential_ref ~ '^[a-z0-9][a-z0-9-]{0,127}$'),
  CHECK (session_encryption_key_ref IS NULL OR session_encryption_key_ref ~ '^[a-z0-9][a-z0-9-]{0,127}$')
);

CREATE UNIQUE INDEX IF NOT EXISTS idx_gateway_identity_configuration_single_active
  ON gateway_identity_configuration_revisions ((true)) WHERE state = 'active';

CREATE INDEX IF NOT EXISTS idx_gateway_identity_configuration_revisions_created
  ON gateway_identity_configuration_revisions(created_at DESC);

CREATE TABLE IF NOT EXISTS gateway_identity_management_requests (
  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)
);
