class UsersController < ApplicationController
  before_action :require_admin, only: [:index, :destroy, :toggle_admin]
  before_action :set_user, only: [:show, :edit, :update, :destroy, :toggle_admin]
  before_action :require_admin_or_owner, only: [:show, :edit, :update]

  def index
    @users = User.all.order(created_at: :desc)
  end

  def show
  end

  def new
    @user = User.new
  end

  def create
    @user = User.new(user_params)
    if @user.save
      session[:user_id] = @user.id
      flash[:notice] = "アカウントを作成しました"
      redirect_to root_path
    else
      render :new, status: :unprocessable_entity
    end
  end

  def edit
  end

  def update
    # パスワードが空の場合は更新しない
    if user_update_params[:password].blank?
      user_update_params.delete(:password)
      user_update_params.delete(:password_confirmation)
    end

    if @user.update(user_update_params)
      flash[:notice] = "ユーザー情報を更新しました"
      redirect_to user_path(@user)
    else
      render :edit, status: :unprocessable_entity
    end
  end

  def destroy
    if @user == current_user
      flash[:alert] = "自分自身を削除することはできません"
      redirect_to users_path
    else
      @user.destroy
      flash[:notice] = "ユーザーを削除しました"
      redirect_to users_path
    end
  end

  def toggle_admin
    if @user == current_user
      flash[:alert] = "自分自身の管理者権限は変更できません"
    else
      @user.update(admin: !@user.admin)
      flash[:notice] = "管理者権限を#{@user.admin? ? '付与' : '削除'}しました"
    end
    redirect_to users_path
  end

  private

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

  def require_admin_or_owner
    unless current_user&.admin? || current_user == @user
      flash[:alert] = "アクセス権限がありません"
      redirect_to root_path
    end
  end

  def user_params
    params.require(:user).permit(:username, :email, :password, :password_confirmation)
  end

  def user_update_params
    # メールアドレスは変更不可
    params.require(:user).permit(:username, :password, :password_confirmation)
  end
end
