module Twitch
  class PasswordsController < Twitch::BaseController
    before_action :set_user
    def change_password
      filtered_params = change_password_params
      unless filtered_params[:new_password].present?
        flash[:danger] = 'Please submit a valid password'
        return redirect_to @user
      end
      success = @user.change_password(filtered_params[:new_password])
      if success
        flash[:success] = 'Successfully changed password'

        track_action! trackable_request
          .assemble_an
          .admin_panel_button(
            button: "change_password",
            user_id: params[:user_id]
          )
      else
        flash[:danger] = 'Failed to change password'
      end
      redirect_to @user
    end

    def force_reset
      success = @user.force_password_reset
      if success
        flash[:success] = 'Successfully forced password reset'

        track_action! trackable_request
          .assemble_an
          .admin_panel_button(
            button: "force_password_reset",
            user_id: params[:user_id]
          )
      else
        flash[:danger] = 'Failed to force password reset'
      end
      redirect_to @user
    end

    def change_password_params
      return {} unless params[:new_password].present?
      filtered_params = params.permit(:new_password)
      filtered_params.require(:new_password)
      filtered_params
    end

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

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

      authorize @user
    end
  end
end
