require "rails_helper"

feature "User creates tags" do
  let(:current_user) { create(:user) }
  let(:project) { create(:project, account: current_user.primary_account) }

  shared_examples "a taggable collection UI", js: true do
    specify do
      sign_in current_user
      visit polymorphic_path [subject.first.project, subject.first.model_name.plural]

      by "adding a tag to multiple releases" do
        select_multiple_releases(subject)
        submit_tags_modal(subject, tags: "Test tag!")
        expect(page).to have_content("Test tag!", count: 5)
      end
    end

    def select_multiple_releases(release)
      all('input[type=checkbox]').each do |checkbox|
        if !checkbox.checked? then 
          checkbox.click
        end
      end

      click_link "Tag All"
    end

    def submit_tags_modal(releases, tags:)
      action = url_for([:tag_multiple, releases.first.model_name.plural, only_path: true])
      tags_form = "form[action='#{action}']"

      within tags_form do
        fill_in "Name", with: tags
        click_button "Add"
      end
    end
  end

  context "for appearance releases" do
    subject! { create_list(:appearance_release, 5, project: project, tags: []) }

    it_behaves_like "a taggable collection UI"
  end

  context "for talent releases" do
    subject! { create_list(:talent_release, 5, project: project, tags: []) }

    it_behaves_like "a taggable collection UI"
  end

  context "for location releases" do
    subject! { create_list(:location_release, 5, project: project, tags: []) }

    it_behaves_like "a taggable collection UI"
  end

  context "for material releases" do
    subject! { create_list(:material_release, 5, project: project, tags: []) }

    it_behaves_like "a taggable collection UI"
  end

  context "for acquired media releases" do
    subject! { create_list(:acquired_media_release, 5, project: project, tags: []) }

    it_behaves_like "a taggable collection UI"
  end

  context "for music releases" do
    subject! { create_list(:music_release, 5, project: project, tags: []) }

    it_behaves_like "a taggable collection UI"
  end
end
