<?php

namespace PortalPeople\AuthRedirect\Plugin;

use Magento\Customer\Model\Authentication;
use PortalPeople\AuthRedirect\Helper\SimpleLoginAttemptHelper;
use Psr\Log\LoggerInterface;

class AuthenticationPlugin
{
    private $loginAttemptHelper;
    private $logger;

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

    public function aroundAuthenticate(
        Authentication $subject,
        \Closure $proceed,
        $customerId,
        $password
    ) {
        try {
            $result = $proceed($customerId, $password);
            
            // If we get here without exception, authentication was successful
            $customer = $this->getCustomerById($customerId);
            if ($customer && $customer->getEmail()) {
                $this->loginAttemptHelper->logAttempt($customer->getEmail(), true);
            }
            
            return $result;
            
        } catch (\Magento\Framework\Exception\InvalidEmailOrPasswordException $e) {
            // Authentication failed
            $customer = $this->getCustomerById($customerId);
            if ($customer && $customer->getEmail()) {
                $this->loginAttemptHelper->logAttempt($customer->getEmail(), false);
            }
            
            throw $e;
        } catch (\Exception $e) {
            // Other authentication errors
            $customer = $this->getCustomerById($customerId);
            if ($customer && $customer->getEmail()) {
                $this->loginAttemptHelper->logAttempt($customer->getEmail(), false);
            }
            
            throw $e;
        }
    }

    private function getCustomerById($customerId)
    {
        try {
            $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
            $customerRepository = $objectManager->get(\Magento\Customer\Api\CustomerRepositoryInterface::class);
            return $customerRepository->getById($customerId);
        } catch (\Exception $e) {
            $this->logger->error('Failed to get customer: ' . $e->getMessage());
            return null;
        }
    }
}
