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

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

  sig { override.void }
  def start_enqueuing
    processed_url_names = T.let(Set.new, T::Set[String])

    loop do
      users =
        Domain::User::FaUser
          .where(state: "ok")
          .order(Arel.sql "json_attributes->>'scanned_page_at' asc nulls first")
          .limit(150)
          .to_a

      if users.empty? ||
           (
             (sfa = users.map(&:scanned_page_at).compact.max) &&
               sfa > 89.days.ago
           )
        break
      end

      users =
        users.reject do |user|
          url_name = user.url_name
          url_name && processed_url_names.include?(url_name)
        end

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

      processed_url_names.merge(users.map(&:url_name).compact)
    end
  end

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