<?php

namespace Artemis\Loyalty\Listeners;

use App\Models\User;
use Illuminate\Support\Str;

class CreateReferralCodeForNewUser
{
    public function handle($event)
    {
        $event->user->update([
            'referral_code' => $this->generateUniqueReferralCode()
        ]);
    }

    protected function generateUniqueReferralCode()
    {
        do {
            $code = Str::upper(Str::random(8));
        } while (User::where('referral_code', $code)->exists());

        return $code;
    }
}
