require "rails_helper"

RSpec.describe BroadcastsChannel, type: :channel do
  let(:broadcast) { create(:broadcast, :with_stream, skip_create_callback: true) }

  before do
    stub_connection
  end

  it "successfully subscribes to public stream" do
    subscribe token: broadcast.token
    expect(subscription).to be_confirmed
    expect(subscription).to have_stream_for(broadcast)
  end

  describe ".broadcast_stream_updates" do
    it "broadcasts to the channel" do
      status_content = ApplicationController.render partial: "broadcasts/broadcast_status", locals: { broadcast: broadcast }
      video_content = ApplicationController.render partial: "broadcasts/video", locals: { broadcast: broadcast }

      expect {
        BroadcastsChannel.broadcast_stream_updates(broadcast)
      }.to have_broadcasted_to(broadcast).with({
        event: "broadcast_stream_update",
        status: broadcast.status,
        playback_url: broadcast.stream_playback_url,
        status_content: status_content,
        video_content: video_content,
        streamer_status: broadcast.streamer_status
      })
    end
  end

  describe '#stream_recording_ready' do
    it 'broadcasts to the channel with the right data' do
      create_list(:broadcast_recording, 1, broadcast: broadcast) 
      recordings = broadcast.broadcast_recordings.paginate(page: 1)
      flash_message = OpenStruct.new(notice: 'Hello world', alert: nil)
      flash_content = ApplicationController.render partial: 'application/flash', locals: { flash: flash_message }
      recordings_content = ApplicationController.render partial: 'broadcasts/broadcast_recordings', locals: { recordings: recordings, broadcast: broadcast }
      recordings_nav_content = ApplicationController.render partial: 'broadcasts/broadcast_recording_nav', collection: recordings, as: :broadcast_recording

      expect {
        BroadcastsChannel.stream_recording_ready(broadcast, recordings, 'Hello world')
      }.to have_broadcasted_to(broadcast).with({
        event: 'stream_recording_ready',
        flash_content: flash_content, 
        recordings_content: recordings_content,
        recordings_nav_content: recordings_nav_content
      })
    end
  end


  describe ".broadcast_file_upload_updates" do
    it 'broadcasts to the channel with the right data' do
      broadcast = create(:broadcast, :with_stream, :with_files, skip_create_callback: true)
      files_content = ApplicationController.render partial: "broadcasts/file", collection: broadcast.files

      expect {
        BroadcastsChannel.broadcast_file_upload_updates(broadcast, broadcast.files, "pagination_content")
      }.to have_broadcasted_to(broadcast).with({
        event: 'file_upload_update',
        broadcast_token: broadcast.token,
        files_content: files_content,
        pagination_content: "pagination_content"
      })
    end
  end
end
