require 'rails_helper'

RSpec.describe Broadcast, type: :model do
  describe "associations" do
    it { is_expected.to belong_to(:project) }
  end

  describe "validations" do
    it { is_expected.to validate_presence_of(:name) }
    it { is_expected.to have_secure_token(:token) }
  end

  describe "enums" do
    it { is_expected.to define_enum_for(:status).with_values([:created, :active, :idle]) }
    it { is_expected.to define_enum_for(:streamer_status).with_values([:idle, :connected, :recording, :disconnected]).with_prefix(:streamer) }
  end

  describe "callbacks" do
    context "#after_create" do
      let(:broadcast) { build(:broadcast, name: "My Broadcast") }
      let(:live_stream_data) { OpenStruct.new(data: OpenStruct.new(id: "stream_id", stream_key: "stream_key")) }
      let(:live_stream_playback_data) { OpenStruct.new(data: OpenStruct.new(id: "playback_id")) }

      it 'triggers create_mux_live_stream' do
        expect(broadcast).to receive(:create_mux_live_stream)

        broadcast.run_callbacks(:create)
      end

      it 'assigns stream_id, stream_key and stream_playback_id to broadcast' do
        allow_any_instance_of(MuxRuby::LiveStreamsApi).to receive(:create_live_stream).and_return(live_stream_data)
        allow_any_instance_of(MuxRuby::LiveStreamsApi).to receive(:create_live_stream_playback_id).and_return(live_stream_playback_data)

        broadcast.save

        expect(broadcast.stream_uid).to eq "stream_id"
        expect(broadcast.stream_key).to eq "stream_key"
        expect(broadcast.stream_playback_uid).to eq "playback_id"
      end
    end

    context "#after_destroy" do
      let(:broadcast) { create(:broadcast, :with_stream, skip_create_callback: true, name: "My Broadcast") }

      it "triggers destroy_mux_live_stream" do
        allow(broadcast).to receive(:destroy_mux_live_stream)
        broadcast.run_callbacks(:destroy)

        expect(broadcast).to have_received(:destroy_mux_live_stream)
      end
    end
  end

  describe "#zoom_meeting_url" do
    it { is_expected.to delegate_method(:zoom_meeting_url).to(:project) }
  end

  describe "#order_by_recent" do
    subject { described_class }
    it { is_expected.to respond_to(:order_by_recent) }
  end
end
