CREATE TABLE IF NOT EXISTS gateway_identity_secret_cleanup_queue (
  secret_ref text PRIMARY KEY CHECK (secret_ref ~ '^[a-z0-9][a-z0-9-]{0,127}$'),
  not_before timestamptz NOT NULL,
  status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending','claimed')),
  claim_token uuid,
  lease_expires_at timestamptz,
  created_at timestamptz NOT NULL DEFAULT now(),
  updated_at timestamptz NOT NULL DEFAULT now(),
  CONSTRAINT gateway_identity_secret_cleanup_claim_check CHECK (
    (status = 'pending' AND claim_token IS NULL AND lease_expires_at IS NULL) OR
    (status = 'claimed' AND claim_token IS NOT NULL AND lease_expires_at IS NOT NULL)
  )
);

CREATE INDEX IF NOT EXISTS idx_gateway_identity_secret_cleanup_due
  ON gateway_identity_secret_cleanup_queue(status, not_before, lease_expires_at, updated_at);
