require "rails_helper"

feature "User imports release templates", type: :feature do
  let(:current_user) { create(:user, :account_manager) }
  let(:project) { create(:project, members: current_user, account: current_user.primary_account) }
  let(:project_one) { create(:project, name: "Avengers", members: [current_user], account: current_user.primary_account) }
  let!(:project_one_template) { create(:contract_template, name: "First Contract Template", fee: 50, release_type: "appearance", project: project_one) }
  let(:project_two) { create(:project, name: "Justice League", members: [], account: current_user.primary_account) }
  let!(:project_two_template) { create(:contract_template, name: "Second Contract Template", fee: 50, release_type: "talent", project: project_two) }

  before do
    sign_in(current_user)
  end

  scenario "importing two existing templates into a project" do
    visit project_contract_templates_path(project)
    click_on "Import Release Template"
    select_templates([project_one_template.id, project_two_template.id])
    click_on "Import Selected Templates"
    expect(page).to have_content("Selected templates were imported with success")
    expect(page).to have_content("First Contract Template")
    expect(page).to have_content("Second Contract Template")
  end

  scenario "preventing import of already imported template" do
    release_template_ids = [project_one_template.id, project_two_template.id]
    project.import_contract_templates(release_template_ids)

    visit project_contract_templates_path(project)
    expect(page).not_to have_button("Import Selected Templates")
  end

  scenario "searching for a template", js: true do
    visit project_contract_templates_path(project)
    click_on "Import Release Template"
    fill_in "query", with: "Second"
    click_on "search-button"
    expect(page).not_to have_content("First Contract Template")
    expect(page).to have_content("Second Contract Template")

    fill_in "query", with: "Avengers"
    click_on "search-button"
    expect(page).to have_content("First Contract Template")
    expect(page).not_to have_content("Second Contract Template")
  end

  private

  def select_templates(template_ids)
    template_ids.each do |id|
      find(:css, "input[name='template_ids[]'][value='#{id}']").set(true)
    end
  end
end