require 'spec_helper'

describe "affiliate visit tracking", :js => true,  :type => :feature, :capybara_feature => true do

  subject { page }

  let(:user) { FactoryGirl.create(:user) }
  let(:partner) { FactoryGirl.create(:affiliate_partner) }
  let(:affiliate_params) { partner.affiliate_query_params }

  before(:each) do
    AffiliatePartner.delete_all
    AffiliateTrafficTotal.delete_all
    AffiliateReferralVisit.delete_all
  end

  before(:all) do
    @old_recaptcha=Rails.application.config.recaptcha_enable
    Rails.application.config.recaptcha_enable=false
  end

  after(:all) do
    Rails.application.config.recaptcha_enable=@old_recaptcha
  end

  # the ways that a user might signup:
  # on free jamtrack redemption flow - this is verified in checkout_spec.rb
  # via facebook
  # /signup
  it "verifies that a signup via /signup page, when coming from a referral, attributes partner" do
    visit '/?' + affiliate_params

    should_be_at_root
    AffiliateReferralVisit.count.should eq(1)

    visit '/signup'
    fill_in "jam_ruby_user[first_name]", with: "Affiliate"
    fill_in "jam_ruby_user[last_name]", with: "Referral"
    fill_in "jam_ruby_user[email]", with: "referral1@jamkazam.com"
    fill_in "jam_ruby_user[password]", with: "jam123"
    fill_in "jam_ruby_user[password_confirmation]", with: "jam123"
    check("jam_ruby_user[terms_of_service]")
    click_button "CREATE ACCOUNT"

    should have_title("JamKazam | Congratulations")

    referral = User.find_by_email('referral1@jamkazam.com')
    referral.affiliate_referral.should eq(partner)
    GenericState.affiliate_tallied_at.should be_nil
    AffiliatePartner.tally_up(referral.created_at.to_date + 1)

    partner.referral_user_count.should eq(0)
    partner.reload
    partner.referral_user_count.should eq(1)

    AffiliateReferralVisit.count.should eq(1)
    AffiliateTrafficTotal.count.should eq(1)
    total = AffiliateTrafficTotal.first
    total.signups.should eq(1)
  end


end
