# typed: strict
class Domain::E621::Task::CollectPostFavsTask
  extend T::Sig
  include HasColorLogger
  include HasMeasureDuration

  sig { params(query: String, start_page: Integer, max_page: Integer).void }
  def run(query:, start_page:, max_page:)
    page = start_page
    while page <= max_page
      url =
        "https://e621.net/posts.json?tags=#{query.gsub(" ", "+")}&limit=320&page=#{page}"
      logger.info "GET page=#{page}, max=#{max_page}, url=#{url}"
      page += 1
      post_jsons =
        measure("GET #{url}") do
          T.cast(
            HTTP
              .headers(
                "User-Agent" => "FurryArchiver",
                "Accept" => "application/json",
              )
              .get(url)
              .parse[
              "posts"
            ],
            T::Array[T::Hash[String, T.untyped]],
          )
        end

      post_jsons.each do |post_json|
        post =
          Domain::E621::TagUtil.initialize_or_update_post(post_json: post_json)
        post.save!
        next if post.scanned_post_favs_at
        Domain::E621::Job::ScanPostFavsJob.perform_now(post: post)
      end
    end
  end
end
