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

  sig { override.params(args: T::Hash[Symbol, T.untyped]).returns(T.untyped) }
  def perform(args)
    post = post_from_args!
    logger.push_tags(make_arg_tag(post))
    file = post.file
    logger.push_tags(make_arg_tag(file)) if file.present?

    if file.present? && file.state == "ok" && file.log_entry_id.present?
      logger.warn("post already has file with 'ok' state, skipping")
      return
    end

    logger.info("scanning post")

    response = http_client.get("https://e621.net/posts/#{post.e621_id}.json")
    post.scan_log_entry = response.log_entry
    post.last_submission_log_entry = response.log_entry

    if response.status_code != 200
      post.state = "scan_error"
      post.scan_error =
        "Error scanning post #{post.e621_id}: #{response.status_code}"
      post.save!
      fatal_error(
        "Error scanning post #{post.e621_id}: #{response.status_code}",
      )
    else
      logger.info("scanned post")
    end

    post_json = JSON.parse(response.body)["post"]
    post =
      Domain::E621::TagUtil.initialize_or_update_post(
        post_json: post_json,
        caused_by_entry: causing_log_entry,
      )
    post.scan_log_entry = response.log_entry
    post.last_submission_log_entry = response.log_entry
  ensure
    post.save! if post
    file.save! if file
  end
end
