<?php

declare(strict_types=1);

namespace App\Application\Security\Events\Auth;

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

final class AuthenticationFailedEvent implements OWASPSecurityEvent
{
    private MaskedEmail $maskedEmail;

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

    public function getOWASPEventIdentifier(): OWASPEventIdentifier
    {
        return OWASPEventIdentifier::authenticationFailure($this->maskedEmail->toString());
    }

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

    public function getDescription(): string
    {
        return "User {$this->maskedEmail->toString()} login failed" .
               ($this->reason ? " - {$this->reason}" : '');
    }

    public function getEventData(): array
    {
        return [
            'email' => $this->maskedEmail->toString(),
            'reason' => $this->reason,
            'failed_attempts' => $this->failedAttempts,
            'failure_reason' => $this->reason ?? 'invalid_credentials',
        ];
    }

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