# typed: false
# frozen_string_literal: true
T.bind(self, T.all(Rake::DSL, Object))

namespace :fingerprint do
  desc "Create missing fingerprints"
  task create_missing: :environment do
    # create thumbnails that do not exist
    relation = Domain::PostFile.where.missing(:fingerprint).includes(:blob)
    pb = ProgressBar.create(total: relation.count)
    relation.find_each do |post_file|
      post_file.create_fingerprint
      pb.progress = [pb.progress + 1, pb.total].min
    end
  end

  task for_posts: :environment do
    ids = ENV["IDS"].split(",")
    pb = ProgressBar.create(total: ids.size)
    ids.each do |id|
      model = DomainController.find_model_from_param(Domain::Post, id)
      model.files.each { |file| file.create_fingerprint }
      pb.progress = [pb.progress + 1, pb.total].min
    end
  end

  task for_users: :environment do
    ids = ENV["IDS"].split(",")
    ids.each do |id|
      user = DomainController.find_model_from_param(Domain::User, id)
      puts "migrating #{id}: #{user.posts.count} posts"
      pb =
        ProgressBar.create(
          total: user.posts.count,
          format: "%t: %c/%C %B %p%% %a %e",
        )
      user
        .posts
        .includes(:files)
        .find_in_batches(batch_size: 10) do |batch|
          ReduxApplicationRecord.transaction do
            batch.each do |post|
              post.files.each do |file|
                file.create_fingerprint unless file.fingerprint
              end
              pb.progress = [pb.progress + 1, pb.total].min
            end
          end
        end
    end
  end
end
