require "rails_helper"

describe AttachRecordingToZoomMeetingJob do
  let(:project) { create(:project) }
  let(:zoom_meeting) { create(:zoom_meeting, project: project) }
  let(:recording_hash) { {'id' => 'recording-id', 'download_url' => 'http://download.url', 'recording_start' => '2020-05-22 16:33:50 UTC', 'recording_end' => '2020-05-22 17:34:06 UTC'} }
  let(:download_token) { 'download_token' }

  before :each do
    allow_any_instance_of(ZoomGateway).to receive(:delete_recording)
  end

  describe ".perform_now" do
    it "downloads the video" do
      allow(zoom_meeting.recording).to receive(:attach)

      expect(URI).to receive(:open).with("http://download.url?access_token=download_token")
      AttachRecordingToZoomMeetingJob.perform_now zoom_meeting, recording_hash, download_token
    end

    it "deletes the recording through the API" do
      stub_uri_open
      allow(zoom_meeting.recording).to receive(:attach).and_return(true)

      expect_any_instance_of(ZoomGateway).to receive(:delete_recording).with(zoom_meeting.api_meeting_id, 'recording-id')
      AttachRecordingToZoomMeetingJob.perform_now zoom_meeting, recording_hash, download_token
    end

    it "attaches downloaded video to recording" do
      allow(zoom_meeting.recording).to receive(:attach)
      stub_uri_open

      AttachRecordingToZoomMeetingJob.perform_now zoom_meeting, recording_hash, download_token
      expect(zoom_meeting.recording).to have_received(:attach).with(hash_including(content_type: 'video/mp4'))
    end
  end

  private

  def stub_uri_open
    url = "http://download.url?access_token=download_token"
    file = double(:file, read: 'stubbed read')
    allow(URI).to receive(:open).with(url).and_return(file)
  end
end
