<?php
declare(strict_types=1);

namespace App\Application\Security\Events\Auth;

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

final class AccountLockedEvent
{
    public function __construct(
        public readonly string $email,
        public readonly string $reason,
        public readonly int $failedAttempts
    ) {}

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

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

    public function getDescription(): string
    {
        return "Account {$this->maskEmail($this->email)} locked";
    }

    public function getEventData(): array
    {
        return [
            'username' => $this->maskEmail($this->email),
            'lock_reason' => $this->reason,
            'failed_attempts' => $this->failedAttempts
        ];
    }

    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;
    }
}
