require "rails_helper"

RSpec.describe Admin::BroadcastsController, type: :controller do
  render_views

  let!(:current_user) { create(:user, :admin) }

  before do
    sign_in(current_user)
    stub_mux_live_stream
  end

  describe "#edit" do
    let(:broadcast) { create(:broadcast) }

    it "returns a successful response" do
      get :edit, params: { id: broadcast }

      expect(response).to be_successful
    end

    it "assigns broadcast" do
      get :edit, params: { id: broadcast }

      expect(assigns(:broadcast)).to eq broadcast
    end
  end

  describe "#update" do
    let(:broadcast) { create(:broadcast) }
  
    it "redirects to broadcasts page" do
      patch :update, params: { id: broadcast, broadcast: broadcast_update_params }
  
      expect(response).to be_redirect
      expect(response).to redirect_to [:admin, broadcast.project.account]
    end
  
    it "sets a flash notice" do
      patch :update, params: { id: broadcast, broadcast: broadcast_update_params }
  
      expect(flash.notice).to eq "The broadcast has been updated"
    end
  
    it "updates the broadcast record" do
      patch :update, params: { id: broadcast, broadcast: broadcast_update_params }
  
      expect(assigns(:broadcast)).to have_attributes(
                                      stream_url_override: "https://example.com/streams/abcd",
                                      stream_key_override: "abcdef",
                                    )
    end
  
    context "when record cannot be saved" do
      before do
        allow_any_instance_of(Broadcast).to receive(:update).and_return(false)
      end
  
      it "re-displays the form" do
        patch :update, params: { id: broadcast, broadcast: broadcast_update_params }
  
        expect(response).to be_successful
        expect(flash.notice).to be_nil
      end
    end
  end

  private

  def broadcast_update_params
    {
      stream_url_override: "https://example.com/streams/abcd",
      stream_key_override: "abcdef",
      director_mode_video_embed: "<iframe>Video player</iframe>",
    }
  end
end
