# typed: strict
class Domain::Fa::Job::UserAvatarJob < Domain::Fa::Job::Base
  extend T::Sig
  queue_as :static_file

  sig { override.params(args: T::Hash[Symbol, T.untyped]).returns(T.untyped) }
  def perform(args)
    avatar = avatar_from_args!
    user = T.cast(avatar.user, Domain::User::FaUser)
    return if buggy_user?(user)

    logger.push_tags(make_arg_tag(avatar), make_arg_tag(user))

    if avatar.state == "ok" && avatar.log_entry.present? && !force_scan?
      logger.info("already have avatar downloaded, skipping")
      return
    end

    avatar_url_str =
      avatar.url_str || "https://a.furaffinity.net/0/#{user.url_name}.gif"
    response = http_client.get(avatar_url_str)
    logger.push_tags(make_arg_tag(response.log_entry))

    avatar.url_str = avatar_url_str
    avatar.last_log_entry = response.log_entry
    avatar.downloaded_at = response.log_entry.created_at&.utc

    case response.status_code
    when 200
      avatar.state = "ok"
      avatar.log_entry = response.log_entry
      logger.info(format_tags("downloaded avatar"))
    when 404
      avatar.state = "file_404"
      avatar.error_message = "http status #{response.status_code}"
      logger.warn(format_tags("404, terminal error state"))
    else
      avatar.state = "http_error"
      avatar.error_message = "http status #{response.status_code}"
      fatal_error(
        format_tags(
          "http #{response.status_code}, log entry #{response.log_entry.id}",
        ),
      )
    end
  ensure
    avatar.save! if avatar
  end
end
