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

  def index
    @users = User.order(created_at: :desc)
                 .by_role(params[:role])
                 .search_email(params[:q])
  end

  def edit
  end

  def update
    # Prevent users from modifying their own role
    if @user == current_user && user_params[:role].present?
      redirect_to admin_users_path, alert: "You cannot modify your own role."
      return
    end

    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
    permitted = params.require(:user).permit(:name, :email, :primary_language)

    # Only allow role if it's a valid role enum value
    if params[:user][:role].present? && User.roles.key?(params[:user][:role])
      permitted[:role] = params[:user][:role]
    end

    permitted
  end
end
