module Bits
  class BadgesController < Bits::BaseController
    before_action :set_badges, only: [:index, :all, :update_badge_tiers, :moderate_badge_tiers]

    def index
      authorize Badge

      if params[:id].present? || params[:user_id].present? || params[:search_query].present?
        return redirect_to(bits_user_badges_path(@user_id)) if @user_id.present?

        flash.now[:error] = 'Error loading Bits badges'
      end
    end

    def all
      authorize Badge

      # load default bits badges
      @default_badges = Badges::Bits.global_display
    end

    def update_badge_tiers
      authorize Badge

      tiers = params[:tiers].map { |tier_threshold, tier_setting| { threshold: tier_threshold.to_i, enabled: tier_setting == 'enabled' } }

      if Badge.update_badge_tiers(@user_id, tiers)
        flash[:success] = "Successfully updated badge tiers in #{@twitch_user.login}'s channel"
      else
        flash[:error] = 'Failed to update badge tiers'
      end

      redirect_back
    end

    def moderate_badge_tiers
      authorize Badge

      tiers_to_moderate = Hash.new { |hash, key| hash[key] = { threshold: key.to_i } }

      if params.dig(:tiers_with_violating_title)
        params[:tiers_with_violating_title].each do |threshold|
          tiers_to_moderate[threshold][:delete_title] = true
        end
      end

      if params.dig(:tiers_with_violating_images)
        params[:tiers_with_violating_images].each do |threshold|
          tiers_to_moderate[threshold][:delete_image] = true
        end
      end

      if tiers_to_moderate.empty?
        flash[:warning] = "No custom badge tiers were selected for moderation."
        return redirect_back
      end

      if Badge.update_badge_tiers(@user_id, tiers_to_moderate.values)
        flash[:success] = "Successfully deleted customizations for #{tiers_to_moderate.size} badge tiers. " \
                          "The change might take a few minutes to show up due to server-side caching."
      else
        flash[:error] = "Failed to delete custom badge tiers"
      end
      redirect_back
    end

    protected

    def set_badges
      authorize Badge

      user_id = params[:id].presence || params[:user_id].presence

      if user_id.present?
        @twitch_user = Twitch::User.find(user_id)
      elsif params[:search_query].present?
        @twitch_user = Twitch::User.all({
          :where => {
            :text => params[:search_query],
            :skip_pagination => true
          }
        }).first
      end

      if @twitch_user.present?
        @user_id = @twitch_user.id
        @badges = Badge.all @twitch_user.id
      end
    end
  end
end
