<?php
declare(strict_types=1);

namespace App\Application\Security;

/**
 * Beispiel für Logeintrag:
 * {
 * 'timestamp': '2025-06-01T00:52:10Z',
 * 'event': 'auth.login.failed',
 * 'ip': '203.0.113.42',
 * 'user_agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)',
 * 'request_uri': '/login',
 * 'method': 'POST',
 * 'user_id': null,
 * 'email': 'j***@example.com',
 * 'session_id': 'abc123',
 * 'referrer': 'https://example.com/login',
 * 'result': 'fail',
 * 'request_id': 'req-3d92fcb45e'
 * }
 *
 */

final readonly class SecurityContext
{
    public function __construct(
        public string             $ip,
        public ?string            $userAgent,
        public string             $method,
        public string             $uri,
        public \DateTimeImmutable $timestamp,
        public ?string            $userId = null,
        public ?string            $sessionId = null,
        public ?string            $referrer = null,
        public ?string            $requestId = null
    ) {}

    public static function fromGlobals(): self
    {
        return new self(
            ip: $_SERVER['REMOTE_ADDR'] ?? 'unknown',
            userAgent: $_SERVER['HTTP_USER_AGENT'] ?? null,
            method: $_SERVER['REQUEST_METHOD'] ?? 'CLI',
            uri: $_SERVER['REQUEST_URI'] ?? '-',
            timestamp: new \DateTimeImmutable(),
            userId: $_SESSION['user_id'] ?? null,
            sessionId: session_id() ?: null,
            referrer: $_SERVER['HTTP_REFERER'] ?? null,
            requestId: $_SERVER['HTTP_X_REQUEST_ID'] ?? bin2hex(random_bytes(8))
        );
    }
}
