<?php

declare(strict_types=1);

namespace Macopedia\OrlenShipping\Observer\Payment;

use Macopedia\OrlenShipping\Helper\Data;
use Macopedia\OrlenShipping\Model\Carrier\OrlenShipping;
use Magento\Framework\App\State;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\OfflinePayments\Model\Cashondelivery;

class Manage implements ObserverInterface
{
    /**
     * @param State $state
     * @param Data $helper
     */
    public function __construct(
        protected readonly State $state,
        protected readonly Data $helper,
    ) {
    }

    /**
     * @inheritDoc
     */
    public function execute(Observer $observer): void
    {
        $paymentMethod = $observer->getData('method_instance')->getCode();
        $quote = $observer->getData('quote');
        $checkResult = $observer->getData('result');

        if (!empty($quote) && $quote->getShippingAddress()->getShippingMethod() !== null) {
            $shippingMethod = $quote->getShippingAddress()->getShippingMethod();
            if (str_contains($shippingMethod, OrlenShipping::CODE)) {
                if ($paymentMethod === Cashondelivery::PAYMENT_METHOD_CASHONDELIVERY_CODE) {
                    $checkResult->setData('is_available', false);
                }
            }
        }
    }
}
