class AnalyzeVideoJob < ApplicationJob
  queue_as :default

  before_perform do |job|
    video = job.arguments.first
    ProjectsChannel.broadcast_video_analysis_update(video)
  end

  def perform(video, reanalysis: false)
    response = BrayniacAI::FacialRecognition.create! VideoAnalysis.new(video, reanalysis)
    
    video.update!({
      analysis_uid: response.job_id,
      analysis_started_at: Time.zone.now,
      analysis_status: :pending,
    })

  rescue StandardError => e
    video.analysis_failure!
    Rails.logger.error("Failed to analyze video(##{video.id})\n" + e.message)
  end

  after_perform do |job|
    video = job.arguments.first
    ProjectsChannel.broadcast_video_analysis_update(video)
  end
end
