require "rails_helper"

feature "User managing project memberships" do
  let(:account) { create(:account) }

  scenario "manager invites an existing team member to another project" do
    manager = create(:user, :manager, accounts: [account], email: "manager@test.com")
    project = create(:project, members: manager, account: account, name: "Project")
    another_user = create(:user, accounts: [account], email: "another.user@test.com")
    another_project = create(:project, members: [manager, another_user], account: account, name: "Another Project")

    sign_in manager
    visit project_project_memberships_path(project)

    expect(page).to have_content "manager@test.com"
    expect(page).not_to have_content "another.user@test.com"

    fill_in invite_email_field, with: "another.user@test.com"
    click_on "Send Invite"

    expect(page).to have_content "User has been invited to the project."
    expect(page).to have_content "another.user@test.com"
  end

  scenario "manager removes an existing team member from a project" do
    manager = create(:user, :manager, accounts: [account], email: "manager@test.com")
    another_user = create(:user, accounts: [account], email: "another.user@test.com")
    project = create(:project, members: [manager, another_user], account: account, name: "Project")

    sign_in manager
    visit project_project_memberships_path(project)

    expect(page).to have_content "manager@test.com"
    expect(page).to have_content "another.user@test.com"
    expect(page).to have_link("Remove", href: project_membership_path(another_user.project_memberships.first))

    click_on "Remove"

    expect(page).to have_content "User has been removed from the project."
    expect(page).not_to have_content "another.user@test.com"
  end

  private

  def invite_email_field
    "project_membership[user_email]"
  end
end
