require "rails_helper"

describe AnalyzeVideoJob do
  describe ".perform_now" do
    it "calls API with video data" do
      video = build_stubbed(:video)
      video_analysis = instance_double(VideoAnalysis, "video_analysis")
      expect(VideoAnalysis).to receive(:new).with(video, false).and_return(video_analysis)

      mock_facial_recognition_create_api_call
      mock_video_update(video)
      
      AnalyzeVideoJob.perform_now video

      expect(BrayniacAI::FacialRecognition).to(
        have_received(:create!).
        with(video_analysis)
      )
    end

    it "calls API with video data and reanalysis flag" do
      video = build_stubbed(:video)
      video_analysis = instance_double(VideoAnalysis, "video_analysis")
      expect(VideoAnalysis).to receive(:new).with(video, true).and_return(video_analysis)

      mock_facial_recognition_create_api_call
      mock_video_update(video)

      AnalyzeVideoJob.perform_now video, reanalysis: true

      expect(BrayniacAI::FacialRecognition).to(
        have_received(:create!).
        with(video_analysis)
      )
    end

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

      freeze_time do
        AnalyzeVideoJob.perform_now video

        expect(video).to(
          have_received(:update!).
          with({
            analysis_uid: "123abc",
            analysis_started_at: Time.zone.now,
            analysis_status: :pending
          })
        )
      end
    end
  end

  private

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

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