class Admin::UsersController < Admin::BaseController
  before_action :set_user, only: [ :edit, :update, :destroy ]

  def index
    @users = User.order(created_at: :desc)
    @users = @users.where(role: params[:role]) if params[:role].present?
    @users = @users.where("email LIKE ?", "%#{params[:q]}%") if params[:q].present?
  end

  def edit
  end

  def update
    if @user.update(user_params)
      redirect_to admin_users_path, notice: "User updated successfully."
    else
      render :edit, status: :unprocessable_entity
    end
  end

  def destroy
    if @user == current_user
      redirect_to admin_users_path, alert: "You cannot delete your own account."
      return
    end

    if @user == User.first
      redirect_to admin_users_path, alert: "Cannot delete the first admin user (system default contact)."
      return
    end

    @user.destroy
    redirect_to admin_users_path, notice: "User deleted successfully."
  end

  private

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

  def user_params
    params.require(:user).permit(:name, :email, :role, :primary_language)
  end
end
