<?php

namespace App\Providers;

use App\Models\Domain;
use App\Observers\DomainObserver;
use Illuminate\Support\ServiceProvider;
use Livewire\Component;
use Livewire\Livewire;

use function Livewire\on;

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

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        Domain::observe(DomainObserver::class);

        // Note: AuthEventListener is auto-discovered by Laravel 11+
        // Do not manually subscribe - it causes duplicate audit log entries
        on('dehydrate', function (Component $component): void {
            static $dispatched = false;

            if ($dispatched) {
                return;
            }

            if (! Livewire::isLivewireRequest()) {
                return;
            }

            if (count(session()->get('filament.notifications') ?? []) <= 0) {
                return;
            }

            $dispatched = true;
            $component->dispatch('notificationsSent');
        });
    }
}
