module Twitch
  class AccountsController < Twitch::BaseController
    before_action :set_user

    def reset
      failures = []

      begin
        success = @user.delete_all_authorizations
        failures << 'Failed to delete all authorizations' unless success
      rescue StandardError
        failures << 'Failed to delete all authorizations'
      end

      begin
        success = @user.delete_all_cookies
        failures << 'Failed to delete user\'s cookies' unless success
      rescue StandardError
        failures << 'Failed to delete user\'s cookies'
      end

      begin
        success = @user.disconnect_chat_sessions
        failures << 'Failed to disconnect user\'s chat sessions' unless success
      rescue StandardError
        failures << 'Failed to disconnect user\'s chat sessions'
      end

      begin
        success = @user.force_password_reset
        failures << 'Failed to force password reset' unless success
      rescue StandardError
        failures << 'Failed to force password reset'
      end

      if !failures.empty?
        flash[:error] = failures.join(', ')
      else
        flash[:success] = 'Successfully revoked a user\'s OAuth tokens, disconnects them from chat, deletes their cookies, and resets their password.'

        track_action! trackable_request
          .assemble_an
          .admin_panel_button(
            button: "reset_compromised_account",
            user_id: params[:user_id]
          )
      end

      redirect_to @user
    end

    private

    def set_user
      @user = User.find params[:user_id]

      if @user.blank?
        flash[:error] = "User not found"
        return redirect_to twitch_users_path
      end

      authorize @user
    end
  end
end
