require File.expand_path(File.dirname(__FILE__) + '/../../test_helper')

class BraintreeBlueTest < ActionDispatch::IntegrationTest
  def setup
    @provider_account, plan = create_provider_account

    @provider_account.settings.allow_finance! unless @provider_account.settings.finance.allowed?
    @provider_account.settings.show_finance! unless @provider_account.settings.finance.visible?

    @buyer_account = Factory(:buyer_account, :provider_account => @provider_account)
    @buyer_account.buy!(plan)
    host! @provider_account.domain
  end

  test "navigate to the correct link" do
    login_with @buyer_account.admins.first.username, 'supersecret'

    get "/admin/account/"
    details_url = "/admin/account/braintree_blue"
    assert_select('a[href=?]', details_url)
  end

  test "credit card stored ok" do
    # stub BrainTreeBlueCrypt.new(current_user).confirm(request) to return struct that answers true to success
    @provider_account.payment_gateway_options[:environment] = :sandbox
    @provider_account.payment_gateway_options[:merchant_id] = "fg74mfhnnrvdbw8t"
    @provider_account.payment_gateway_options[:public_key] = "kr9r6kkq9f2kck9z"
    @provider_account.payment_gateway_options[:private_key] = "kzyp5sngm67h8vw5"
      login_with @buyer_account.admins.first.username, 'supersecret'
      assert_equal nil, @buyer_account.credit_card_partial_number

  end

  test "credit card not stored" do
    # stub BrainTreeBlueCrypt.new(current_user).confirm(request) to return struct that answers false to success
    login_with @buyer_account.admins.first.username, 'supersecret'
    PaymentGateways::BrainTreeBlueCrypt.any_instance.stubs(:confirm).returns(false)
    get "/admin/account/braintree_blue/hosted_success"
  end

  test "bad credentials" do
    # stub BrainTreeBlueCrypt.new(current_user).confirm(request) to return nil
    PaymentGateways::BrainTreeBlueCrypt.any_instance.stubs(:confirm).returns(nil)
  end

  # test "invalid merchant id redirects to show" do
  #   login_with @buyer_account.admins.first.username, 'supersecret'
  #   get "/admin/account/braintree_blue/edit"
  #   assert_redirected_to admin_account_braintree_blue_url
  #   assert_equal 'Invalid merchant id' , flash[:error]
  # end

  def create_provider_account
    provider_account = Factory(:provider_with_billing, :payment_gateway_type => :braintree_blue, :payment_gateway_options => {:merchant_id => 'foo', :public_key => 'bar', :private_key => 'baz'})
    provider_account.billing_strategy = Factory(:postpaid_with_charging)
    provider_account.payment_gateway_type = :braintree_blue

    plan = Factory(:application_plan, :issuer => provider_account.default_service)
    [provider_account, plan]
  end
end
