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

    def disable
      if @user.two_factor_required?
        flash[:error] = "Two factor is required for this user"
        return redirect_to @user
      end

      response = Passport::TwoFactor.disable_2fa(user_id: params[:user_id])

      if response.disabled_at.present?
        audit = History::Audit.new(
          action: History::AUDIT_ACTION_DISABLE_2FA,
          user_type: History::AUDIT_LDAP_USER,
          user_id: current_user.ldap_login,
          resource_type: History::AUDIT_TWITCH_USER,
          resource_id: response.user_id
        )
        History::AddAudit.add(audit)
        flash[:success] = "Successfully removed two factor"
      else
        errs = "Unable to disable two factor"
        if response.errors.present?
          errs =
            "Unable to disable two factor: " +
            response
            .errors
            &.full_messages
            &.map {|e| e unless e.respond_to?(:map)}
            &.compact
            &.to_sentence
        end
        flash[:error] = errs
      end
      redirect_to @user
    end

    protected

    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
