<?php

namespace App\Providers;

use App\Listeners\LogFailedLoginAttempt;
use App\Models\Consultation;
use App\Models\TimelineUpdate;
use App\Notifications\QueueFailureNotification;
use App\Observers\ConsultationObserver;
use App\Observers\TimelineUpdateObserver;
use Illuminate\Auth\Events\Failed;
use Illuminate\Queue\Events\JobFailed;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        Event::listen(Failed::class, LogFailedLoginAttempt::class);

        Consultation::observe(ConsultationObserver::class);
        TimelineUpdate::observe(TimelineUpdateObserver::class);

        Queue::failing(function (JobFailed $event) {
            if (! config('libra.notifications.system_notifications_enabled')) {
                return;
            }

            $adminEmail = config('libra.notifications.admin_email');

            if (empty($adminEmail)) {
                return;
            }

            Notification::route('mail', $adminEmail)
                ->notifyNow(new QueueFailureNotification($event));
        });
    }
}
