<?php

declare(strict_types=1);

namespace App\Application\Security\Events\Session;

use App\Application\Security\ValueObjects\{OWASPEventIdentifier, OWASPLogLevel};

final class SessionHijackingDetectedEvent
{
    public function __construct(
        public readonly string $email,
        public readonly string $sessionId,
        public readonly string $evidence,
        public readonly ?string $suspiciousIp = null
    ) {
    }

    public function getOWASPEventIdentifier(): OWASPEventIdentifier
    {
        return OWASPEventIdentifier::sessionHijacking($this->maskEmail($this->email));
    }

    public function getOWASPLogLevel(): OWASPLogLevel
    {
        return OWASPLogLevel::FATAL;
    }

    public function getDescription(): string
    {
        return "Session hijacking detected for user {$this->maskEmail($this->email)}";
    }

    public function getEventData(): array
    {
        return [
            'username' => $this->maskEmail($this->email),
            'session_id' => hash('sha256', $this->sessionId),
            'evidence' => $this->evidence,
            'suspicious_ip' => $this->suspiciousIp,
        ];
    }

    private function maskEmail(string $email): string
    {
        if (! filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return $email;
        }

        [$local, $domain] = explode('@', $email, 2);
        $maskedLocal = substr($local, 0, 2) . str_repeat('*', max(0, strlen($local) - 2));

        return $maskedLocal . '@' . $domain;
    }
}
