namespace :counters do
  # Generic counter reset helper that works with any model
  def reset_model_counters(model_class, counter_names, batch_size: 1000)
    counter_names = Array(counter_names)
    model_name = model_class.name.demodulize.underscore
    counter_desc =
      counter_names
        .map { |n| n.to_s.sub("#{model_name}_", "").sub("user_", "") }
        .join(" and ")

    total = model_class.count
    puts "Resetting #{counter_desc} counter cache for #{total} #{model_name.pluralize}..."

    pb = ProgressBar.create(total: total, format: "%t: %c/%C %B %p%% %a %e")

    model_class
      .pluck(:id)
      .each_slice(batch_size) do |ids|
        model_class.transaction do
          ids.each do |id|
            model_class.reset_counters(id, *counter_names)
            pb.increment
          end
        end
      end

    puts "Done!"
  end

  namespace :domain do
    namespace :user do
      def reset_user_counters(counter_names)
        reset_model_counters(Domain::User, counter_names)
      end

      desc "Reset all user counter caches"
      task all: :environment do
        reset_user_counters(
          %i[
            user_post_creations
            user_post_favs
            user_user_follows_from
            user_user_follows_to
          ],
        )
      end

      desc "Reset post-related counter caches only (creations and favs)"
      task posts: :environment do
        reset_user_counters(%i[user_post_creations user_post_favs])
      end

      desc "Reset follow-related counter caches only (follows_from and follows_to)"
      task follows: :environment do
        reset_user_counters(%i[user_user_follows_from user_user_follows_to])
      end

      desc "Reset user_post_creations_count counter cache"
      task user_post_creations_count: :environment do
        reset_user_counters(:user_post_creations)
      end

      desc "Reset user_post_favs_count counter cache"
      task user_post_favs_count: :environment do
        reset_user_counters(:user_post_favs)
      end

      desc "Reset user_user_follows_from_count counter cache"
      task user_user_follows_from_count: :environment do
        reset_user_counters(:user_user_follows_from)
      end

      desc "Reset user_user_follows_to_count counter cache"
      task user_user_follows_to_count: :environment do
        reset_user_counters(:user_user_follows_to)
      end
    end
  end
end
