module Twitch
  class UserRenamesController < Twitch::BaseController
    before_action :set_user

    def new
    end

    def create
      params[:ldap_login] = current_user.ldap_login

      if @user.rename(params)
        flash[:success] = "Successfully renamed #{@user.login}"
        redirect_to @user
      else
        flash[:rename_error] = @user.errors.full_messages.to_sentence
        redirect_to new_override_twitch_user_rename_path(new_login: params[:new_login])
      end
    end

    def new_override
      @error_message = flash[:rename_error]
    end

    def create_override
      params[:ldap_login] = current_user.ldap_login
      params[:admin_override] = true

      if @user.rename(params)
        flash[:success] = "Successfully renamed #{@user.login}"
      else
        flash[:error] = @user.errors.full_messages.to_sentence
      end

      redirect_to @user
    end

    protected

    def set_user
      @user = User.find params[:user_id]

      if @user.blank?
        flash[:error] = "User not found"
        return redirect_to twitch_users_path
      end

      authorize @user
    end
  end
end
