<?php
declare(strict_types=1);

namespace App\Application\Security\Events\Input;

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

final class XssAttemptEvent implements OWASPSecurityEvent
{
    private ?MaskedEmail $maskedEmail;

    public function __construct(
        public readonly string $attackPayload,
        public readonly string $targetField,
        public readonly string $xssType,
        public readonly ?string $email = null
    ) {
        $this->maskedEmail = $this->email ? MaskedEmail::fromString($this->email) : null;
    }

    public function getOWASPEventIdentifier(): OWASPEventIdentifier
    {
        return OWASPEventIdentifier::maliciousInput('xss_attempt');
    }

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

    public function getDescription(): string
    {
        return "XSS attempt detected: {$this->xssType}";
    }

    public function getEventData(): array
    {
        return [
            'attack_payload' => $this->sanitizePayload($this->attackPayload),
            'target_field' => $this->targetField,
            'xss_type' => $this->xssType,
            'username' => $this->maskedEmail?->toString() ?? 'anonymous'
        ];
    }

    public function getMaskedEmail(): ?MaskedEmail
    {
        return $this->maskedEmail;
    }

    private function sanitizePayload(string $payload): string
    {
        // HTML-Tags entfernen aber Struktur beibehalten für Analyse
        return substr(htmlspecialchars($payload, ENT_QUOTES, 'UTF-8'), 0, 200);
    }
}
