<?php
declare(strict_types=1);

namespace App\Application\Security\Events\Web;

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

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

    public function __construct(
        public readonly string $requestPath,
        public readonly string $method,
        public readonly ?string $expectedToken = null,
        public readonly ?string $providedToken = null,
        public readonly ?string $email = null
    ) {
        $this->maskedEmail = $this->email ? MaskedEmail::fromString($this->email) : null;
    }

    public function getOWASPEventIdentifier(): OWASPEventIdentifier
    {
        return OWASPEventIdentifier::csrfViolation($this->requestPath);
    }

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

    public function getDescription(): string
    {
        return "CSRF token validation failed for {$this->method} {$this->requestPath}";
    }

    public function getEventData(): array
    {
        return [
            'request_path' => $this->requestPath,
            'method' => $this->method,
            'expected_token_hash' => $this->expectedToken ? hash('sha256', $this->expectedToken) : null,
            'provided_token_hash' => $this->providedToken ? hash('sha256', $this->providedToken) : null,
            'username' => $this->maskedEmail?->toString() ?? 'anonymous'
        ];
    }

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