<?php
declare(strict_types=1);

namespace App\Application\Security\Events\Auth;

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

final class PasswordChangedEvent
{
    public function __construct(
        public readonly string $email,
        public readonly string $method = 'self_service'
    ) {}

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

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

    public function getDescription(): string
    {
        return "User {$this->maskEmail($this->email)} changed password";
    }

    public function getEventData(): array
    {
        return [
            'username' => $this->maskEmail($this->email),
            'change_method' => $this->method
        ];
    }

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