# frozen_string_literal: true

class DownloadRawFile < InteractorBase
  requires :key

  def call
    context.file = s3_object.get(response_target: tempfile)
                            .body
  end

  protected

  def s3_object
    @s3_object ||= S3_CLIENT.bucket(S3_BUCKET_NAME).object(key)
  end

  def tempfile
    FileUtils.mkdir_p(raw_folder)
    Tempfile.new([raw_basename, raw_extension], raw_folder, encoding: 'ascii-8bit')
  end

  def raw_folder
    "#{Dir.tmpdir}/#{File.dirname(key)}"
  end

  def raw_basename
    File.basename(s3_object.public_url, '.*')
  end

  def raw_extension
    File.extname(s3_object.public_url)
  end
end
