require 'test_helper'

class Buyers::AccountsControllerTest < ActionController::TestCase
  disable_transactional_fixtures!

  context "params" do

    setup do
      @buyer = Factory :buyer_account
      @provider = @buyer.provider_account
      @request.host = @provider.self_domain

      login_as(@provider.admins.first)
    end

    # regression test for: https://github.com/3scale/system/issues/2567
    should "not raise exception on update if params[:account] is nil" do
      put :update, id: @buyer
      assert_equal "Required parameter missing: account", response.body
    end
  end


  test 'billing address extra field and webhooks' do
    provider = FactoryGirl.create(:provider_account)
    FactoryGirl.create(:fields_definition, account: provider,
                       target: 'Account', name: 'billing_address', read_only: true)

    provider.settings.allow_web_hooks!
    FactoryGirl.create(:webhook, account: provider, account_created_on: true, active: true)

    User.current = login_provider provider

    assert_difference provider.buyers.method(:count) do
      assert_queued WebHookJob do
        put :create, account: {
            org_name: 'hello', org_legaladdress: 'address',
            user: { username: 'hello', email: 'foo@example.com', password: 'password'}
        }
      end

      assert_response :redirect
    end

    account = Account.last!

    assert_equal 'approved', account.state
    assert_equal 'hello', account.org_name
    assert_equal 'address', account.org_legaladdress
  end

  test 'checks if link under number of applications is correct' do
    application = FactoryGirl.create(:application)
    provider = application.user_account.provider_account
    provider.settings.allow_multiple_applications!
    login_provider(provider)

    get :index

    assert_select %{td a[href="#{admin_buyers_account_applications_path(application.user_account)}"]}, text: '1'
  end
end
