<?php
declare(strict_types=1);

namespace PortalPeople\AuthRedirect\Controller\Ajax;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\Framework\Controller\ResultFactory;
use Psr\Log\LoggerInterface;
use PortalPeople\AuthRedirect\Model\LoginAttemptLogger;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Customer\Model\Session;
use Magento\Framework\Data\Form\FormKey\Validator;
use Magento\Framework\Exception\LocalizedException;
use PortalPeople\AuthRedirect\Helper\SimpleLoginAttemptHelper;

class Login extends Action implements HttpPostActionInterface
{
    private AccountManagementInterface $accountManagement;
    private LoginAttemptLogger $loginAttemptLogger;
    private LoggerInterface $logger;
    private JsonFactory $jsonFactory;
    private Session $customerSession;
    private RequestInterface $request;
    private Validator $formKeyValidator;
    private SimpleLoginAttemptHelper $loginAttemptHelper;

    public function __construct(
        Context $context,
        AccountManagementInterface $accountManagement,
        LoginAttemptLogger $loginAttemptLogger,
        LoggerInterface $logger,
        JsonFactory $jsonFactory,
        Session $customerSession,
        RequestInterface $request,
        Validator $formKeyValidator,
        SimpleLoginAttemptHelper $loginAttemptHelper
    ) {
        parent::__construct($context);
        $this->accountManagement = $accountManagement;
        $this->loginAttemptLogger = $loginAttemptLogger;
        $this->logger = $logger;
        $this->jsonFactory = $jsonFactory;
        $this->customerSession = $customerSession;
        $this->request = $request;
        $this->formKeyValidator = $formKeyValidator;
        $this->loginAttemptHelper = $loginAttemptHelper;
    }

    public function execute()
    {
        $this->logger->debug('🔐 Entered AuthRedirect login controller');

        $result = $this->jsonFactory->create();

        $this->logger->info('Login attempt started', [
            'is_ajax' => $this->request->isXmlHttpRequest(),
            'method' => $this->request->getMethod()
        ]);

        // CSRF Protection
        if (!$this->request->isXmlHttpRequest()) {
            $this->logger->warning('Non-AJAX request to login endpoint');
            return $result->setData([
                'success' => false,
                'message' => __('Invalid request.')
            ]);
        }

        if (!$this->formKeyValidator->validate($this->request)) {
            $this->logger->warning('Invalid form key in login request');
            return $result->setData([
                'success' => false,
                'message' => __('Invalid form key.')
            ]);
        }

        $email = trim($this->request->getParam('email'));
        $password = $this->request->getParam('password');

        if (empty($email) || empty($password)) {
            $this->logger->warning('Empty email or password in login request');
            return $result->setData([
                'success' => false,
                'message' => __('Email and password are required.')
            ]);
        }

        $this->logger->info('Processing login for email: ' . $email);

        // Rate limiting check
        if ($this->loginAttemptHelper->isRateLimited($email)) {
            $this->logger->warning('Rate limited login attempt', ['email' => $email]);
            $this->loginAttemptHelper->logAttempt($email, false);
            return $result->setData([
                'success' => false,
                'message' => __('Too many login attempts. Please try again later.')
            ]);
        }

        try {
            $customer = $this->accountManagement->authenticate($email, $password);
            $this->customerSession->setCustomerDataAsLoggedIn($customer);
            $this->customerSession->regenerateId();
            
            // Log successful attempt
            $this->logger->info('Successful login', ['email' => $email, 'customer_id' => $customer->getId()]);
            $this->loginAttemptHelper->logAttempt($email, true);

            return $result->setData([
                'success' => true,
                'message' => __('Login successful.'),
                'redirect_url' => '/checkout'
            ]);

        } catch (LocalizedException $e) {
            // Log failed attempt
            $this->logger->warning('Failed login attempt', ['email' => $email, 'error' => $e->getMessage()]);
            $this->loginAttemptHelper->logAttempt($email, false);
            
            return $result->setData([
                'success' => false,
                'message' => $e->getMessage()
            ]);
        } catch (\Exception $e) {
            // Log failed attempt
            $this->logger->error('Login error', ['email' => $email, 'error' => $e->getMessage()]);
            $this->loginAttemptHelper->logAttempt($email, false);
            
            return $result->setData([
                'success' => false,
                'message' => __('An error occurred during login. Please try again.')
            ]);
        }
    }
}
