require "rails_helper"

RSpec.feature "User can update his profile", type: :feature do
  let(:user) { create(:user, :with_name) }

  before do
    sign_in(user)
  end

  scenario "user clicks profile dropdown" do
    visit signed_in_root_path

    click_on "John Doe"

    expect(page).to have_link("Profile Settings", href: profile_path)
    expect(page).to have_link("Sign Out", href: session_path)
  end

  scenario "visits profile page" do
    visit profile_path

    expect(page).to have_content("First name")
    expect(page).to have_content("Last name")
  end

  scenario "updates first and last name" do
    visit profile_path

    within "form" do
      fill_in "First name", with: "John"
      fill_in "Last name", with: "Doe"
      click_on "Update Profile"
    end

    expect(page).to have_content("John Doe")
    expect(page).to have_content("JD")
  end

  scenario "updates avatar" do
    visit profile_path

    within "form" do
      attach_file "user[avatar]", Rails.root.join(file_fixture("person_photo.png")), visible: false
      fill_in "First name", with: "John"
      fill_in "Last name", with: "Doe"
      click_on "Update Profile"
    end

    expect(page).to have_content("Profile has been updated successfully")
    expect(page).to have_content("John Doe")
    expect(page).to have_photo("person_photo.png")
  end

  context "user is admin" do
    let(:user) { create(:user, :with_name, :admin) }

    scenario "admin visits user listing" do
      visit admin_users_path
  
      expect(page).to have_content("First Name")
      expect(page).to have_content("Last Name")
      expect(page).to have_content("John")
      expect(page).to have_content("Doe")
    end

    scenario "admin clicks profile dropdown" do
      visit admin_users_path

      click_on "John Doe"
      
      expect(page).to have_link("BIG Admin", href: admin_signed_in_root_path)
      expect(page).to have_link("Profile Settings", href: profile_path)
      expect(page).to have_link("Account Settings", href: account_auths_path)
      expect(page).to have_link("Sign Out", href: session_path)
    end
  end

  context "user is account manager" do
    let(:user) { create(:user, :with_name, :account_manager) }

    scenario "account manager clicks profile dropdown" do
      visit signed_in_root_path

      click_on "John Doe"

      expect(page).to have_link("Profile Settings", href: profile_path)
      expect(page).to have_link("Account Settings", href: account_auths_path)
      expect(page).to have_link("Sign Out", href: session_path)
    end
  end

  private

  def have_photo(filename)
    have_selector("img[src*='#{filename}']")
  end
end
