require 'rails_helper'

RSpec.describe AnalyzeAudioJob, type: :job do
  describe ".perform_now" do
    it "calls API" do
      video = build_stubbed(:video)
      audio_analysis = instance_double(AudioAnalysis, "audio_analysis")
      expect(AudioAnalysis).to receive(:new).with(video).and_return(audio_analysis)

      mock_audio_recognition_create_api_call
      mock_video_update(video)
      
      AnalyzeAudioJob.perform_now video

      expect(BrayniacAI::AudioRecognition).to(
        have_received(:create!).
        with(audio_analysis)
      )
    end

    it "saves data about the analysis" do
      video = build_stubbed(:video)
      mock_audio_recognition_create_api_call(job_uid: "123abc")
      mock_video_update(video)

      freeze_time do
        AnalyzeAudioJob.perform_now video

        expect(video).to(
          have_received(:update!).
          with({
            audio_analysis_uid: "123abc",
            audio_analysis_started_at: Time.zone.now,
            audio_analysis_status: :pending
          })
        )
      end
    end
  end

  private

  def mock_audio_recognition_create_api_call(job_uid: "test")
    double("response", job_id: job_uid).tap do |api_response|
      allow(BrayniacAI::AudioRecognition).to(
        receive(:create!).
        and_return(api_response)
      )
    end
  end

  def mock_video_update(video)
    allow(video).to receive(:update!)
  end
end
