require "rails_helper"

RSpec.describe StreamNotificationsController, type: :controller do
  render_views

  let!(:broadcast) { create(:broadcast, :with_stream, skip_create_callback: true, name: "Live Stream") }
  let(:active_status) { {type: "video.live_stream.active", object: { id: "mux_stream" }} }
  let(:disconnected_status) { {type: "video.live_stream.disconnected", object: { id: "mux_stream" }} }
  let(:idle_status) { {type: "video.live_stream.idle", object: { id: "mux_stream" }} }
  let(:asset_ready) { {
    type: "video.asset.static_renditions.ready",
    object: { id: "asset_uid" },
    data: {
      playback_ids: [
        {id: "playback_uid"}
      ],
      static_renditions: {
        files: [{name: "high.mp4"}]
      }
    },
    stream_notification: {
      data: {
        live_stream_id: "mux_stream"
      }
    }
  } }

  describe "#create" do
    before do
      allow(BroadcastsChannel).to receive(:broadcast_stream_updates).with(be_kind_of(Broadcast))
      allow(BroadcastsChannel).to receive(:stream_recording_ready)
    end

    it "updates the broadcast when active status is received in notification" do
      post :create, params: active_status

      expect(broadcast.reload).to be_active
      expect(BroadcastsChannel).to have_received(:broadcast_stream_updates).with(be_kind_of(Broadcast))
    end

    it "updates the broadcast when disconnected status is received in notification" do
      post :create, params: disconnected_status

      expect(broadcast.reload).to be_streamer_disconnected
      expect(BroadcastsChannel).to have_received(:broadcast_stream_updates).with(be_kind_of(Broadcast))
    end

    it "updates the broadcast when idle status is received in notification" do
      post :create, params: idle_status

      expect(broadcast.reload).to be_idle
      expect(BroadcastsChannel).to have_received(:broadcast_stream_updates).with(be_kind_of(Broadcast))
    end

    it "creates a broadcast recording when static_renditions.ready is received in notification" do
      expect {
        post :create, params: asset_ready
      }.to change(BroadcastRecording, :count).by(1)

      expect(BroadcastsChannel).to have_received(:stream_recording_ready)
    end
  end

  after do
    # Set the callback again or it will affect other test cases where the callback is required
    Broadcast.set_callback(:create, :after, :create_mux_live_stream)
  end
end
