module Users
  class RegistrationsController < Devise::RegistrationsController
    def anonymous_sign_up
      anonymous_client = User.find_or_create_by!(
        anonymous: true,
        email: "#{anonymous_session_id}@anonymous.dev"
      ) do |new_anonymous_client|
        new_anonymous_client.assign_attributes(
          role: :client,
          first_name: "Anonymous",
          last_name: anonymous_session_id,
          password: "12345678",
          password_confirmation: "12345678",
          confirmed_at: Time.current,
          locale: I18n.default_locale
        )
      end

      sign_in(anonymous_client)

      redirect_to root_path
    end

    def anonymous_create_account
      return head :unauthorized unless user_signed_in?

      if request.post?
        @user = User.client.create(sign_up_params)
        if @user.persisted?
          sign_out
          redirect_to confirmation_sent_path(@user.confirmation_token)
        else
          render status: :unprocessable_entity
        end
      else
        @user = User.client.new
      end
    end

    protected

    def after_inactive_sign_up_path_for(resource)
      confirmation_sent_path(resource.confirmation_token)
    end

    private

    def sign_up_params
      params.require(:user).permit(:first_name, :last_name, :email, :gender, :password, :password_confirmation)
    end
  end
end
