# typed: strict
class Domain::UserAvatarJob < Scraper::JobBase
  abstract!
  queue_as :static_file

  sig { override.params(args: T::Hash[Symbol, T.untyped]).returns(T.untyped) }
  def perform(args)
    avatar = avatar_from_args!
    logger.push_tags(make_arg_tag(avatar))

    url_str = avatar.url_str
    if url_str.blank?
      logger.warn("avatar has no url_str")
      return
    end

    response = http_client.get(url_str)
    logger.tagged(make_arg_tag(response.log_entry)) do
      self.first_log_entry ||= response.log_entry
      avatar.last_log_entry = response.log_entry

      case response.status_code
      when 200
        avatar.state = "ok"
        avatar.error_message = nil
        avatar.downloaded_at = response.log_entry.created_at&.utc
        avatar.log_entry = response.log_entry
        logger.info("downloaded avatar")
      when 404
        avatar.state = "file_404"
        avatar.error_message = "http #{response.status_code}"
        logger.info("avatar 404")
      else
        avatar.state = "http_error"
        avatar.error_message = "http #{response.status_code}"
        fatal_error(
          "http #{response.status_code}, log entry #{response.log_entry.id}",
        )
      end
    end
  ensure
    avatar.save! if avatar
  end
end
