<?php

namespace App\Listeners;

use App\Model\AuditLogin;
use Illuminate\Auth\Events\Login;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use Modules\Admin\Entities\Admin;

class RecordSuccessLoginAttempt
{
    /**
     * Create the event listener.
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     */
    public function handle(Login $event): void
    {
        $ip = request()->ip();

        $user = $event->user;
        $user->last_login_at = now();
        $user->save();

        $username = $user->username ?: $user->email;

        $throttle_key = Str::transliterate(Str::lower($username) . '|' . $ip);

        AuditLogin::create([
            'admin_id' => $user?->id,
            'email' => $username,
            'ip_address' => $ip,
            'has_remember_me' => $event->remember,
            'has_failed' => false,
            'throttle_hits' => RateLimiter::attempts($throttle_key)
        ]);
    }
}
