<?php

namespace App\Listeners\Accounts;

use App\Events\Accounts\UserEvent;
use App\Events\Accounts\UserHasRegistered;
use App\Events\Accounts\UserInvited;
use App\Models\UserEmailVerification;
use App\Notifications\InvitationEmail;
use App\Notifications\VerifyEmail;

class UserEventHandler {

    /**
     * @param UserEvent $event
     */
    public function handle(UserEvent $event): void {

        if ($event instanceof UserHasRegistered) {
            $attempts = UserEmailVerification::where('email', $event->getData()->email);

            if ($attempts !== null && !$event->getData()->hasVerifiedEmail()) {
                $event->getData()->notify(new VerifyEmail($attempts->first()));
                $attempts->first()->update(['is_sent' => true]);
            }

        }

        if ($event instanceof UserInvited) {
            $event->getData()->notify(new InvitationEmail($event));
        }

    }
}
