export async function startVerification(redirectUrl) {
  const configuration = readConfiguration();
  const callback = validateRedirectUrl(redirectUrl);
  const state = randomBytes(32).toString('base64url');
  const accessToken = await requestAccessToken(configuration);

  // Both return URLs belong to the one callback route you supplied.
  const successUrl = completionUrl(callback, state, 'success');
  const failureUrl = completionUrl(callback, state, 'failure');
  const started = await requestJson('start', configuration, {
    country: recipe.country,
    kyc_policy: recipe.policy,
    redirect_url_success: successUrl,
    redirect_url_fail: failureUrl,
  }, accessToken, [state]);

  if (typeof started.body.start_idv_uri !== 'string') {
    throw new BackendFailure('The start response has no browser URL.', started);
  }
  let browserUrl;
  try {
    browserUrl = new URL(started.body.start_idv_uri);
  } catch (cause) {
    throw new BackendFailure('The start response contains an invalid browser URL.',
        { ...started, cause: String(cause) }, started.credentials);
  }
  if (!['http:', 'https:'].includes(browserUrl.protocol)) {
    throw new BackendFailure('The browser verification URL must use HTTP(S).', started);
  }

  // Keep this object in the same user's backend session, never in the browser.
  return {
    state,
    expiresAt: Date.now() + 15 * 60 * 1000,
    consumed: false,
    callbackUrl: callback.href,
    startIdvUri: started.body.start_idv_uri,
    accessToken,
    configuration,
  };
}
