class Admin::UsersController < ApplicationController
  include Pagy::Backend

  before_action :set_user, only: [ :show, :update ]
  before_action :authorize!

  def index
    # @users = User.all.order(:lastname, :firstname)
    @q = User.ransack(params[:q])
    @q.sorts = "id asc" if @q.sorts.empty?
    @pagy, @records = pagy(@q.result(distinct: true), limit: 20)
  end

  def edit
  end

  def show
  end

  def new
  end

  def create
  end

  def update
    authorize! @user, to: :change_role?
    if @user.update(user_params)
      respond_to do |format|
        format.html { redirect_back(fallback_location: admin_users_path) }
      end
    else
        render :index, status: :unprocessable_entity
    end
  end

  private

  def set_user
    @user = User.find(params[:id])
  end

  def user_params
    params.require(:user).permit(:role)
  end
end
