module Sessions
  class Stop
    def initialize(session)
      @session = session
    end

    def call
      cancel_timeout_job
      Sessions::RegiaAccess.revoke!(@session)
      @session.end_stream!
      complete_youtube_broadcast! if @session.youtube_broadcast_id.present?

      recording = Recordings::FinalizeSession.new(@session).call
      if recording
        Recordings::UploadJob.perform_async(@session.id)
      else
        Mediamtx::Client.new.delete_path(@session)
      end

      log_event("ended")
      SessionChannel.broadcast_message(@session, { type: "stream_event", event: "ended" })
      @session
    end

    private

    def cancel_timeout_job
      return if @session.timeout_job_id.blank?

      Sidekiq::ScheduledSet.new.find_job(@session.timeout_job_id)&.delete
    end

    def log_event(type)
      @session.stream_events.create!(event_type: type, occurred_at: Time.current, metadata: {})
    end

    def complete_youtube_broadcast!
      Youtube::BroadcastService.new(@session.match.team).complete_broadcast!(@session.youtube_broadcast_id)
    rescue Youtube::BroadcastService::Error => e
      Rails.logger.warn("[Sessions::Stop] YouTube complete: #{e.message}")
    end
  end
end
