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

use Magento\Checkout\Api\Data\ShippingInformationInterface;
use Magento\Checkout\Model\ShippingInformationManagement;
use Magento\Framework\Exception\LocalizedException;
use PortalPeople\DisabledPostcodes\Model\Config;
use PortalPeople\DisabledPostcodes\Model\PostcodeMatcher;

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

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

    public function beforeSaveAddressInformation(
        ShippingInformationManagement $subject,
        int $cartId,
        ShippingInformationInterface $addressInformation
    ): array {
        $shippingAddress = $addressInformation->getShippingAddress();
        if (!$shippingAddress) {
            return [$cartId, $addressInformation];
        }

        $storeId = 0;
        if (method_exists($shippingAddress, 'getStoreId')) {
            $storeId = (int)($shippingAddress->getStoreId() ?: 0);
        }
        if (!$this->config->isEnabled($storeId)) {
            return [$cartId, $addressInformation];
        }

        $postcode = (string)$shippingAddress->getPostcode();
        $result = $this->matcher->checkPostcode($postcode, $storeId);

        if (!empty($result['is_excluded'])) {
            throw new LocalizedException(__($this->config->getBlockedCheckoutMessage($storeId)));
        }

        return [$cartId, $addressInformation];
    }
}
