<?php

declare(strict_types=1);

namespace App\Application\Security\Events\File;

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

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

    public function __construct(
        public readonly string $filename,
        public readonly string $mimeType,
        public readonly int $fileSize,
        public readonly string $suspicionReason,
        public readonly ?string $email = null
    ) {
        $this->maskedEmail = $this->email ? MaskedEmail::fromString($this->email) : null;
    }

    public function getOWASPEventIdentifier(): OWASPEventIdentifier
    {
        return OWASPEventIdentifier::fileUploadFailure($this->filename);
    }

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

    public function getDescription(): string
    {
        return "Suspicious file upload: {$this->filename}";
    }

    public function getEventData(): array
    {
        return [
            'filename' => $this->sanitizeFilename($this->filename),
            'mime_type' => $this->mimeType,
            'file_size' => $this->fileSize,
            'suspicion_reason' => $this->suspicionReason,
            'username' => $this->maskedEmail?->toString() ?? 'anonymous',
        ];
    }

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

    private function sanitizeFilename(string $filename): string
    {
        return preg_replace('/[^\w\.\-]/', '_', $filename);
    }
}
