module ZuoraConnect::Controllers::Helpers

def new_instance(id, zuora_entity_id, rest_domain, tenant_id: nil, task_data: nil, retry_count: 0)

def new_instance(id, zuora_entity_id, rest_domain, tenant_id: nil, task_data: nil, retry_count: 0)
  app_instance = ZuoraConnect::AppInstance.new(
    :id => id,
    :api_token => generate_token,
    :token => generate_token,
    :oauth_expires_at => Time.now + 1000.years,
    :zuora_domain => rest_domain,
    :zuora_entity_ids => [zuora_entity_id]
  )
  app_instance[:zuora_tenant_ids] = [tenant_id.to_s] if tenant_id.present?
  if task_data.nil?
    # no encryption
    app_instance['zuora_logins'] = task_data
  else
    # kms encrypt
    app_instance.zuora_logins = task_data
  end
  begin
    app_instance.save(:validate => false)
  rescue ActiveRecord::RecordNotUnique
    raise if retry_count > 1
    Thread.current[:appinstance] = nil
    session['appInstance'] = nil
    render 'zuora_connect/static/error_handled', :locals => {
      :title => 'Application could not create unique tokens.',
      :message => 'Please contact support or retry launching application.'
    }, :layout => false
    return
  end
  app_instance
end