# typed: true
class Domain::Twitter::ApiController < ApplicationController
  skip_before_action :verify_authenticity_token, only: %i[enqueue_objects]

  def enqueue_objects
    @enqueue_counts ||= Hash.new { |h, k| h[k] = 0 }

    names = (params[:names] || [])
    names.each { |name| defer_user_timeline_scan(name, true) }
    enqueue_deferred!
    render json: @enqueue_counts.to_json
  end

  private

  def defer_user_timeline_scan(name, highpri)
    defer_manual(
      Domain::Twitter::Job::UserTimelineTweetsJob,
      { name: name },
      highpri ? -16 : -6,
    )
  end

  def defer_manual(klass, args, priority, queue = nil)
    @@enqueue_deduper ||= Set.new
    return unless @@enqueue_deduper.add?([klass, args, priority])

    @deferred_jobs ||= []
    @deferred_jobs << [klass, args, priority, queue]
    @enqueue_counts[klass] += 1
  end

  def enqueue_deferred!
    GoodJob::Bulk.enqueue do
      while job = (@deferred_jobs || []).shift
        klass, args, priority, queue = job
        klass.set(priority: priority, queue: queue).perform_later(args)
      end
    end
  end

  def time_ago_or_never(time)
    if time
      helpers.time_ago_in_words(time, include_seconds: true) + " ago"
    else
      "never"
    end
  end
end
