require 'rails_helper'

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

  describe "validations" do
    subject { described_class.new(asset_uid: "asset_uid", asset_playback_uid: "playback_uid", file_name: "medium.mp4") }
    it { is_expected.to validate_uniqueness_of(:asset_uid) }
  end

  describe "#delegations" do
    it { should delegate_method(:name).to(:broadcast).with_prefix(:broadcast) }
  end

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

  describe "#download_url" do
    let(:broadcast) { create(:broadcast, :with_stream, skip_create_callback: true, name: "My Broadcast") }
    let(:broadcast_recording) { create(:broadcast_recording, broadcast: broadcast) }

    it "should have a download url" do
      download_file_name = broadcast_recording.send(:download_file_name)
      expect(broadcast_recording.download_url).to eq("https://stream.mux.com/asset_playback_uid/high.mp4?download=#{download_file_name}")
    end
  end

  describe "#download_file_name" do
    it "includes the name of the live stream and the created datetime" do
      broadcast = create(:broadcast, skip_create_callback: true, name: "My Broadcast")
      recording = create(:broadcast_recording, broadcast: broadcast, created_at: DateTime.new(2020, 05, 14, 15, 30, 00))
      file_name = recording.download_file_name

      expect(file_name).to eq "my-broadcast_date_2020-05-14_time_15-30-00"
    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
