<?php

namespace App\Providers;

use App\Helpers\AuditLogger;
use Illuminate\Auth\Events\Failed;
use Illuminate\Auth\Events\Login;
use Illuminate\Auth\Events\Logout;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event to listener mappings for the application.
     *
     * @var array<class-string, array<int, class-string>>
     */
    protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
    ];

    /**
     * Register any events for your application.
     */
    public function boot(): void
    {
        Event::listen(Login::class, function (Login $event) {
            if (!$event->user) {
                return;
            }

            AuditLogger::log('auth', $event->user->id, 'login', null, [
                'user_id' => $event->user->id,
                'name' => trim(($event->user->first_name ?? '') . ' ' . ($event->user->last_name ?? '')),
                'email' => $event->user->email,
                'ip' => request()?->ip(),
                'remember' => (bool) $event->remember,
            ]);
        });

        Event::listen(Logout::class, function (Logout $event) {
            if (!$event->user) {
                return;
            }

            AuditLogger::log('auth', $event->user->id, 'logout', null, [
                'user_id' => $event->user->id,
                'name' => trim(($event->user->first_name ?? '') . ' ' . ($event->user->last_name ?? '')),
                'email' => $event->user->email,
                'ip' => request()?->ip(),
            ]);
        });

        Event::listen(Failed::class, function (Failed $event) {
            AuditLogger::log('auth', 0, 'login_failed', null, [
                'attempted_email' => $event->credentials['email'] ?? null,
                'ip' => request()?->ip(),
                'guard' => $event->guard,
            ]);
        });
    }

    /**
     * Determine if events and listeners should be automatically discovered.
     */
    public function shouldDiscoverEvents(): bool
    {
        return false;
    }
}
