# typed: strict
class Domain::E621::Job::PostsIndexJob < Domain::E621::Job::Base
  queue_as :e621

  sig { override.params(args: T::Hash[Symbol, T.untyped]).returns(T.untyped) }
  def perform(args)
    response = http_client.get("https://e621.net/posts.json")

    if response.status_code != 200
      fatal_error(
        "non 200 response for /posts.json: #{response.status_code.to_s.underline}",
      )
    end

    posts_json =
      T.cast(
        JSON.parse(response.body)["posts"],
        T::Array[T::Hash[String, T.untyped]],
      )

    e621_posts =
      posts_json.map do |post_json|
        Domain::E621::TagUtil.initialize_or_update_post(
          post_json: post_json,
          caused_by_entry: causing_log_entry,
        )
      end

    created_posts = []
    updated_posts = []
    seen_posts = []

    e621_posts.each do |e621_post|
      created_posts << e621_post if e621_post.new_record?
      updated_posts << e621_post if e621_post.changed?
      seen_posts << e621_post
      e621_post.save!
    end

    logger.info(
      "#{updated_posts.count} updated, #{created_posts.count} created, #{seen_posts.count} seen",
    )
  end
end
