require "rails_helper"

RSpec.describe FileInfosController, type: :controller do
  render_views

  let(:current_user) { create(:user) }
  let(:project) { create(:project, account: current_user.accounts.first) }
  let(:acquired_media_release) { create(:acquired_media_release, project: project) }

  before do
    sign_in(current_user)
  end

  shared_examples "a file infoable releases controller" do
    describe "#edit" do
      it "responds successfully" do
        get :edit, params: { "#{subject.model_name.param_key}_id" => subject }

        expect(response).to be_successful
      end
    end

    describe "#update" do
      context "when releasable updated successfully" do
        it "responds with a redirect" do
          patch :update, params: { "#{subject.model_name.param_key}_id": subject, subject.model_name.param_key => release_params }

          expect(response).to be_redirect
          expect(response).to redirect_to [project, subject.model_name.plural]
          expect(flash.notice).to eq(t("file_infos.update.notice"))
        end

        it "enqueues tagging job" do
          expect {
            patch :update, params: { "#{subject.model_name.param_key}_id": subject, subject.model_name.param_key => {} }
          }.to have_enqueued_job(SetTagsForReleasableJob).with(subject.class.last)
        end
      end
    end

    context "when releasable NOT updated successfully" do
      before do
        allow_any_instance_of(subject.class).to receive(:update).and_return(false)
      end

      it "renders edit with flash message" do
        patch :update, params: { "#{subject.model_name.param_key}_id": subject, subject.model_name.param_key => release_params }

        expect(controller).to have_rendered(:edit)
      end

      it "does not enqueue tagging job" do
        expect {
          patch :update, params: { "#{subject.model_name.param_key}_id": subject, subject.model_name.param_key => release_params }
        }.not_to have_enqueued_job(SetTagsForReleasableJob)
      end
    end
  end

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

    it_behaves_like "a file infoable releases controller"
  end

  private

  def release_params
    files = 2.times.map { Rack::Test::UploadedFile.new(file_fixture("audio.mp3"), "audio/mp3") }

    { file_infos_attributes: files }
  end
end
