<?php
namespace PortalPeople\DisabledPostcodes\Plugin\Checkout;

use Magento\Framework\Exception\LocalizedException;
use Magento\Quote\Model\Quote;
use Magento\Quote\Model\QuoteManagement;
use PortalPeople\DisabledPostcodes\Model\Config;
use PortalPeople\DisabledPostcodes\Model\PostcodeMatcher;

class QuoteManagementPlugin
{
    private PostcodeMatcher $matcher;
    private Config $config;

    public function __construct(PostcodeMatcher $matcher, Config $config)
    {
        $this->matcher = $matcher;
        $this->config = $config;
    }

    public function beforeSubmit(QuoteManagement $subject, Quote $quote, array $orderData = []): array
    {
        $shippingAddress = $quote->getShippingAddress();
        if (!$shippingAddress) {
            return [$quote, $orderData];
        }

        $storeId = (int)$quote->getStoreId();
        if (!$this->config->isEnabled($storeId)) {
            return [$quote, $orderData];
        }

        $postcode = (string)$shippingAddress->getPostcode();
        $result = $this->matcher->checkPostcode($postcode, $storeId);
        if (!empty($result['is_excluded'])) {
            throw new LocalizedException(__($this->config->getBlockedCheckoutMessage($storeId)));
        }

        return [$quote, $orderData];
    }
}
