<?php

declare(strict_types=1);

namespace App\Listeners;

use App\Models\LoginHistory;
use App\Models\TrustedDevice;
use Laravel\Fortify\Events\ValidTwoFactorAuthenticationCodeProvided;

class HandleTwoFactorAuthenticated
{
    public function handle(ValidTwoFactorAuthenticationCodeProvided $event): void
    {
        $request = request();

        if (! $request->boolean('trust_device')) {
            return;
        }

        $user = $event->user;
        $ip = $request->ip() ?? '127.0.0.1';
        $userAgent = $request->userAgent() ?? '';

        $deviceHash = LoginHistory::generateDeviceHash($userAgent, $ip);

        // Parse a friendly device name from the user agent
        $deviceName = $this->resolveDeviceName($userAgent);

        TrustedDevice::query()->updateOrCreate(
            [
                'user_id' => $user->id,
                'device_hash' => $deviceHash,
            ],
            [
                'device_name' => $deviceName,
                'ip_address' => $ip,
                'last_used_at' => now(),
                'expires_at' => now()->addDays(30),
            ]
        );
    }

    private function resolveDeviceName(string $userAgent): string
    {
        // Extract browser
        $browser = 'Unknown Browser';
        $browserPatterns = [
            'Edge' => '/Edg[e\/]/',
            'Chrome' => '/Chrome\//',
            'Firefox' => '/Firefox\//',
            'Safari' => '/Safari\//',
            'Opera' => '/OPR\//',
        ];

        foreach ($browserPatterns as $name => $pattern) {
            if (preg_match($pattern, $userAgent)) {
                $browser = $name;
                break;
            }
        }

        // Extract OS
        $os = 'Unknown OS';
        $osPatterns = [
            'Windows' => '/Windows/',
            'macOS' => '/Macintosh/',
            'Linux' => '/Linux/',
            'Android' => '/Android/',
            'iOS' => '/iPhone|iPad/',
        ];

        foreach ($osPatterns as $name => $pattern) {
            if (preg_match($pattern, $userAgent)) {
                $os = $name;
                break;
            }
        }

        return "{$browser} on {$os}";
    }
}
