<?php

declare(strict_types=1);

namespace PortalPeople\AuthRedirect\Plugin;

use Magento\Customer\Model\Account\Redirect as AccountRedirect;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\UrlInterface;
use Magento\Checkout\Helper\Cart;
use Magento\Framework\Controller\Result\RedirectFactory;

class CustomerRedirectPlugin
{
    private RequestInterface $request;
    private UrlInterface $urlBuilder;
    private Cart $cartHelper;
    private RedirectFactory $redirectFactory;

    public function __construct(
        RequestInterface $request,
        UrlInterface $urlBuilder,
        Cart $cartHelper,
        RedirectFactory $redirectFactory
    ) {
        $this->request = $request;
        $this->urlBuilder = $urlBuilder;
        $this->cartHelper = $cartHelper;
        $this->redirectFactory = $redirectFactory;
    }

    public function afterGetRedirect(
        AccountRedirect $subject,
        $result
    ) {
        try {
            // Only apply custom redirect if the request came from /authredirect page
            $isAuthRedirect = $this->request->getHeader('X-Auth-Redirect') || 
                             (strpos($this->request->getServer('HTTP_REFERER', ''), '/authredirect') !== false);
            
            if (!$isAuthRedirect) {
                return $result; // Normal login flow, don't interfere
            }
            
            // Get cart helper via ObjectManager as fallback
            $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
            $cartHelper = $objectManager->get(\Magento\Checkout\Helper\Cart::class);
            
            // Check if customer has items in cart
            if ($cartHelper->getItemsCount() > 0) {
                // Create a new redirect to checkout
                return $this->redirectFactory->create()->setUrl($this->urlBuilder->getUrl('checkout'));
            }
        } catch (\Exception $e) {
            // If cart check fails, continue with normal flow
        }
        return $result;    }}