require 'test_helper'

class ApiDocs::ServicesControllerTest < ActionDispatch::IntegrationTest

  def setup
    provider = FactoryGirl.create(:provider_account)

    login_provider provider

    host! provider.admin_domain
    ApiDocs::ServicesController.instance_variable_set(:@api_files, nil)
  end

  def test_index_and_show
    get api_docs_services_path(format: :json)
    index_result = JSON.parse(response.body)

    assert_response :success
    assert_equal ['host', 'apis'], index_result.keys
    assert_equal 4, index_result['apis'].count

    index_result['apis'].each do |api|
      get api_docs_service_path(format: :json, id: api['system_name'])
      show_result = JSON.parse(response.body)

      assert_response :success
      assert show_result.has_key?('basePath')
      assert show_result.has_key?('apis')
    end
  end

  def test_index_and_show_with_finance
    # I really do not like this, looks ugly, hacky
    # Reloading because of constants changes
    # Maybe change the controller so it can be more testable
    Rails.application.config.three_scale.stubs(finance_enabled: false)

    get '/api_docs/services.json'
    assert_not_match '/api_docs/services/billing_api.json', response.body

    get '/api_docs/services/billing_api.json'
    assert_response :not_found

    Rails.application.config.three_scale.unstub(:finance_enabled)
    get '/api_docs/services.json'
    assert_match '/api_docs/services/billing_api.json', response.body

    get '/api_docs/services/billing_api.json'
    assert_response :success

  end

  def test_record_not_found
    get api_docs_service_path(format: :json, id: 'alaska-api')
    assert_response :not_found
  end

  class ApiFileTest < ActiveSupport::TestCase

    ApiFile = ApiDocs::ServicesController::ApiFile

    def test_backend_base_host
      System::Application.config.stubs(backend_client: { url: 'alaska-localhost:3001', host: 'alaska.com' })
      api_json = ApiFile.new('doc.xml', 'service_management_api').json
      assert_equal 'alaska-localhost:3001', api_json['basePath']

      System::Application.config.stubs(backend_client: { host: 'alaska.com' })
      api_json = ApiFile.new('doc.xml', 'service_management_api').json
      assert_equal 'https://alaska.com', api_json['basePath']
    end
  end

  class ClassMethods < ActiveSupport::TestCase

    def test_file_does_not_exist
      assert_raise(ApiDocs::ServicesController::ApiFileDoesNotExist) do
        ApiDocs::ServicesController.expects(:api_names).returns(['alaska-api'])
        ApiDocs::ServicesController.verify_accessible_api_files_exist!
      end
    end
  end
end
