<?php

namespace PortalPeople\AuthRedirect\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use PortalPeople\AuthRedirect\Helper\SimpleLoginAttemptHelper;
use Psr\Log\LoggerInterface;

class LoginFailedObserver implements ObserverInterface
{
    private $loginAttemptHelper;
    private $logger;

    public function __construct(
        SimpleLoginAttemptHelper $loginAttemptHelper,
        LoggerInterface $logger
    ) {
        $this->loginAttemptHelper = $loginAttemptHelper;
        $this->logger = $logger;
    }

    public function execute(Observer $observer)
    {
        try {
            $username = $observer->getEvent()->getUserName();
            if ($username) {
                $this->loginAttemptHelper->logAttempt($username, false);
                $this->logger->info('Failed login logged', ['username' => $username]);
            }
        } catch (\Exception $e) {
            $this->logger->error('Failed to log failed login: ' . $e->getMessage());
        }
    }
}
