# typed: strict
class Tasks::Fa::EnqueueDueUserFavsScansTask < EnqueueJobBase
  extend T::Sig
  include HasColorLogger

  sig { override.returns(String) }
  def progress_key
    "task-fa-enqueue-due-user-favs-scans"
  end

  sig { override.void }
  def start_enqueuing
    loop do
      users =
        Domain::User::FaUser
          .where(state: "ok")
          .order(Arel.sql "json_attributes->>'scanned_favs_at' asc nulls first")
          .limit(10)

      users.each do |user|
        enqueue do
          logger.tagged(
            make_arg_tag(user),
            make_tag(
              "scanned_favs_at",
              time_ago_in_words(user.scanned_favs_at),
            ),
          ) do
            logger.info("enqueuing favs job")
            Domain::Fa::Job::FavsJob.perform_later({ user: })
          end
        end
      end

      if users.empty? ||
           ((sfa = users.first&.scanned_favs_at) && sfa > 14.days.ago)
        break
      end
    end
  end

  sig { override.returns(Integer) }
  def queue_size
    GoodJob::Job.where(
      job_class: "Domain::Fa::Job::FavsJob",
      performed_at: nil,
      error: nil,
    ).count
  end
end
