require "test_helper"

class MarketoClientTest < ActiveSupport::TestCase

  def setup
    @marketo_settings =  {
      base_url: "https://666-666-666.marketo-hell.com",
      client_id: "theMarketoKey",
      client_secret: "theMarketoSecret"
    }

    @marketo_client = MarketoClient.new(@marketo_settings)

    @marketo_authorization = { 'Authorization' => "Bearer 123456:ab" }
    @marketo_client.access_token = "123456:ab"
    @marketo_response_success = {
      success: true,
      result: [{ id: 1 }]
    }

  end

  test "Initialize" do
    assert_raise(KeyError){MarketoClient.new({})}
    assert_raise(KeyError){MarketoClient.new({base_url: "foo"})}
    assert_raise(KeyError){MarketoClient.new({base_url: "foo", client_id: "bar"})}
    MarketoClient.new(@marketo_settings)
  end

  test "Create Lead" do

    attributes = {
      first_name: "Archibald",
      last_name: "Haddock"
    }
    body = {
      action: 'createOrUpdate',
      input: [attributes]
    }

    endpoint = URI.join(@marketo_settings[:base_url], "/rest/v1/leads.json")

    stub_request(:post, endpoint.to_s)
      .with(:body => JSON.generate(body), :headers => @marketo_authorization)
      .to_return(:status => 200, :body => JSON.generate(@marketo_response_success) , :headers => {})

    @marketo_client.create_lead(attributes)

  end

  test "Update Lead" do

    attributes = {
      first_name: "Jake",
      last_name: "The Dog"
    }

    body = {
      action: 'updateOnly',
      input: [attributes]
    }

    endpoint = URI.join(@marketo_settings[:base_url], "/rest/v1/leads.json")

    stub_request(:post, endpoint.to_s)
      .with(:body => JSON.generate(body), :headers => @marketo_authorization)
      .to_return(:status => 200, :body => JSON.generate(@marketo_response_success) , :headers => {})

    @marketo_client.update_lead(attributes)

  end

  test "Associate Lead" do

    lead_id = "12345"
    mkt_cookie = "theBloodyCookie"

    endpoint = URI.join(@marketo_settings[:base_url], "/rest/v1/leads/#{lead_id}/associate.json")
    endpoint.query = {cookie: mkt_cookie, access_token: "123456:ab"}.to_query

    stub_request(:post, endpoint.to_s)
      .to_return(:status => 200, :body => JSON.generate(@marketo_response_success) , :headers => {})

    @marketo_client.associate_lead(lead_id, mkt_cookie)

  end


end
