export async function completeVerification(callbackUrl, journey) {
  const callback = validateCompletion(callbackUrl, journey);
  journey.consumed = true;

  if (callback.searchParams.get('tomo_outcome') !== 'success') {
    throw new BackendFailure('Verification returned through the failure URL.');
  }

  // URLSearchParams decodes once. Do not call decodeURIComponent again.
  const ppidValues = callback.searchParams.getAll('ppid');
  if (ppidValues.length !== 1 || ppidValues[0].length === 0) {
    throw new BackendFailure('A successful callback must contain one ppid.');
  }
  const encryptedPpid = ppidValues[0];

  // The API bearer stays the OAuth access_token, never callback token or key.
  const result = await requestJson('result', journey.configuration, {
    user_id: encryptedPpid,
    country: recipe.country,
    policy: recipe.policy,
  }, journey.accessToken);

  // This policy returns the latest completed KR certificate result.
  // It does not identify a particular concurrent authentication attempt.
  return {
    response: result.body,
    rawResponse: result.rawBody,
    approved: result.body.result?.kyc?.status === 'approved',
  };
}
