<?php

namespace App\Listeners;

use App\Events\EmailVerificationEvent;
use App\Mail\EmailVerification;
use App\Models\OtpVerification;
use Illuminate\Mail\Mailer;

class EmailVerificationListener
{
    /**
     * Create the event listener.
     */
    public function __construct(private readonly Mailer $mailer)
    {
        //
    }

    /**
     * Handle the event.
     */
    public function handle(EmailVerificationEvent $event): void
    {
        // Store ...
        OtpVerification::createOrUpdate($event->otp, null, $event->email);

        try {
            $this->mailer->send(new EmailVerification(
                $event->email,
                $event->otp,
            ));
        } catch (\Exception $exception) {
            log_debug(
                exception: $exception,
                prefix: 'EmailVerificationListener::handle -- Unable to send verification to ::' . $event->email
            );
        }
    }
}
