<?php

declare(strict_types=1);

namespace App\Service;

/**
 * Derives a short, human-readable label ("Type · OS · Browser") from a raw
 * User-Agent string, used to add forensic context to audit log entries.
 * Heuristic on purpose — enough to tell a phone from a desktop and identify
 * OS/browser families on shared accounts.
 */
class UserAgentParser
{
    public function parse(?string $userAgent): ?string
    {
        if (null === $userAgent) {
            return null;
        }

        $ua = trim($userAgent);
        if ('' === $ua) {
            return null;
        }

        return implode(' · ', [
            $this->detectType($ua),
            $this->detectOs($ua),
            $this->detectBrowser($ua),
        ]);
    }

    private function detectType(string $ua): string
    {
        if (1 === preg_match('/iPad|Tablet/i', $ua)) {
            return 'Tablette';
        }

        if (1 === preg_match('/Mobile|Android|iPhone|iPod/i', $ua)) {
            return 'Mobile';
        }

        return 'Ordinateur';
    }

    private function detectOs(string $ua): string
    {
        // Order matters: iOS before macOS (iOS UAs contain "Mac OS X"),
        // Android before Linux (Android UAs contain "Linux").
        return match (true) {
            1 === preg_match('/iPhone|iPad|iPod/i', $ua)   => 'iOS',
            1 === preg_match('/Android/i', $ua)            => 'Android',
            1 === preg_match('/Windows/i', $ua)            => 'Windows',
            1 === preg_match('/Mac OS X|Macintosh/i', $ua) => 'macOS',
            1 === preg_match('/Linux/i', $ua)              => 'Linux',
            default                                        => 'Autre',
        };
    }

    private function detectBrowser(string $ua): string
    {
        // Order matters: Edge/Opera contain "Chrome" and "Safari";
        // Chrome contains "Safari". Match the most specific first.
        return match (true) {
            1 === preg_match('/Edg/i', $ua)           => 'Edge',
            1 === preg_match('/OPR|Opera/i', $ua)     => 'Opera',
            1 === preg_match('/Firefox|FxiOS/i', $ua) => 'Firefox',
            1 === preg_match('/Chrome|CriOS/i', $ua)  => 'Chrome',
            1 === preg_match('/Safari/i', $ua)        => 'Safari',
            default                                   => 'Autre',
        };
    }
}
