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.project, subject.model_name.plural]

      by "adding tag" do
        open_tags_modal(subject)
        submit_tags_modal(subject, tags: "Test tag!")
        expect(page).to have_content("Test tag!")
        click_button "Close"
        within "##{ActionController::Base.helpers.dom_id(subject, "tags_preview")}" do
          expect(page).to have_content("Test tag!")
        end
      end

      by "removing tag" do
        open_tags_modal(subject)
        submit_tags_modal(subject, tags: "Test tag!")
        remove_tags
        expect(page).not_to have_content("Test tag!")
        click_button "Close"
        within "##{ActionController::Base.helpers.dom_id(subject, "tags_preview")}" do
          expect(page).not_to have_content("Test tag!")
        end
      end
    end

    def open_tags_modal(release)
      click_button "Manage"
      click_link "Tags"
    end

    def submit_tags_modal(release, tags:)
      action = url_for([release, :acts_as_taggable_on_tags, only_path: true])
      tags_form = "form[action='#{action}']"

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

    def remove_tags
      click_link "Remove"
    end
  end

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

    it_behaves_like "a taggable collection UI"
  end

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

    it_behaves_like "a taggable collection UI"
  end

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

    it_behaves_like "a taggable collection UI"
  end

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

    it_behaves_like "a taggable collection UI"
  end

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

    it_behaves_like "a taggable collection UI"
  end

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

    it_behaves_like "a taggable collection UI"
  end

  context "for medical releases" do
    subject! { create(:medical_release, project: project, tags: []) }

    it_behaves_like "a taggable collection UI"
  end
end
