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

  def index
    @users = filtered_users.order("email")
  end

  def new
    @user = build_user
    @accounts = accounts
  end

  def create
    auth_params = user_create_params.slice(:account_id, :role)

    @user = authorize sign_up(user_create_params.except(:account_id, :role))

    if @user.valid?
      account = accounts.find(auth_params[:account_id])
      @user.account_auths << AccountAuth.create(user: @user, account: account, role: auth_params[:role])
      UserMailer.welcome(@user, account).deliver_later
      redirect_to admin_users_path, notice: t(".notice")
    else
      @accounts = accounts
      render :new
    end
  end

  def edit
    @accounts = accounts
  end

  def update
    set_user_password

    if @user.update(user_update_params.except(:password))
      redirect_to admin_users_path, notice: t(".notice")
    else
      @accounts = accounts
      render :edit
    end
  end

  def destroy
    @user = authorize User.find(params[:id])
    @user.destroy

    redirect_to admin_users_path, alert: t(".alert")
  end

  private

  def set_user
    @user = find_user
  end

  def accounts
    policy_scope Account
  end

  def users
    policy_scope User
  end

  def find_user
    authorize users.find(params[:id])
  end

  def build_user(params = {})
    authorize users.new(params)
  end

  def user_create_params
    params.require(:user).permit(:email, :password, :admin, :account_id, :role)
  end

  def user_update_params
    params.require(:user).permit(:email, :admin, :password)
  end

  def set_user_password
    if user_update_params[:password].present?
      Oath::Services::PasswordReset.new(@user, user_update_params[:password]).perform
    end
  end

  def filtered_users
    params[:query].present? ? users.search(params[:query]) : users
  end
end
