<?php

declare(strict_types=1);

namespace App\Application\Security\Events\Session;

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

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

    public function __construct(
        public readonly ?string $email,
        public readonly string $sessionId,
        public readonly int $inactivityDuration,
        public readonly string $reason = 'timeout'
    ) {
        $this->maskedEmail = $this->email ? MaskedEmail::fromString($this->email) : null;
    }

    public function getOWASPEventIdentifier(): OWASPEventIdentifier
    {
        return OWASPEventIdentifier::sessionTimeout($this->maskedEmail !== null ? $this->maskedEmail->toString() : 'anonymous');
    }

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

    public function getDescription(): string
    {
        return "Session timeout for user " . ($this->maskedEmail !== null ? $this->maskedEmail->toString() : 'anonymous');
    }

    public function getEventData(): array
    {
        return [
            'username' => $this->maskedEmail !== null ? $this->maskedEmail->toString() : 'anonymous',
            'session_id' => hash('sha256', $this->sessionId),
            'inactivity_duration' => $this->inactivityDuration,
            'timeout_reason' => $this->reason,
        ];
    }

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