<?php
declare(strict_types=1);

namespace Autogedal\CheckoutFix\Plugin;

use Magento\Quote\Model\QuoteRepository;
use Magento\Quote\Api\Data\CartInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\App\ResourceConnection;
use Psr\Log\LoggerInterface;
use Magento\Framework\Exception\LocalizedException;

class QuoteRepositoryPlugin
{
    public function __construct(
        private ResourceConnection $resourceConnection,
        private LoggerInterface $logger
    ) {
    }

    /**
     * Check if quote has recent orders before returning it as active
     */
    public function afterGetActive(QuoteRepository $subject, CartInterface $result, $cartId, array $sharedStoreIds = []): CartInterface
    {
        // Check if this quote has any orders placed recently
        if ($this->hasRecentOrders((int)$result->getId())) {
            $this->logger->warning('Quote ' . $result->getId() . ' has recent orders but is still active. Setting as inactive.');
            
            // Set the quote as inactive to prevent further processing
            $result->setIsActive(false);
        }
        
        return $result;
    }
    
    /**
     * Check if quote has orders created in the last 10 minutes
     */
    private function hasRecentOrders(int $quoteId): bool
    {
        $connection = $this->resourceConnection->getConnection();
        
        $select = $connection->select()
            ->from('sales_order', ['entity_id'])
            ->where('quote_id = ?', $quoteId)
            ->where('created_at > DATE_SUB(NOW(), INTERVAL 10 MINUTE)')
            ->limit(1);
            
        $orderId = $connection->fetchOne($select);
        
        if ($orderId) {
            $this->logger->info('Quote ' . $quoteId . ' has recent order ID: ' . $orderId);
            return true;
        }
        
        return false;
    }
}