# typed: strict
class Domain::Fa::Job::ScanFileJob < Domain::Fa::Job::Base
  queue_as :static_file
  include Domain::StaticFileJobHelper

  sig { override.params(args: T::Hash[Symbol, T.untyped]).returns(T.untyped) }
  def perform(args)
    file =
      T.cast(args[:file] || args[:post_file], T.nilable(Domain::PostFile)) ||
        begin
          post = args[:post]
          if post.nil?
            if args[:fa_id]
              logger.error "no post model - fa_id: #{args[:fa_id]}, enqueue scan"
              defer_job(Domain::Fa::Job::ScanPostJob, { fa_id: args[:fa_id] })
            else
              fatal_error("no post model or fa_id")
            end
            return
          end
          post =
            if post.is_a?(Domain::Post::FaPost)
              post
            else
              fatal_error(
                "invalid post model: #{post.class}, expected Domain::Post::FaPost",
              )
            end
          post.file
        end

    file = T.must(file)
    download_post_file(file)
  ensure
    file.save! if file
  end
end
