<?php

declare(strict_types=1);

namespace Macopedia\OrlenShipping\Plugin;

use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\Service\OrderService;

class OrderServicePlugin
{
    /**
     * @param OrderRepositoryInterface $orderRepository
     * @param CartRepositoryInterface $cartRepository
     */
    public function __construct(
        protected readonly OrderRepositoryInterface $orderRepository,
        protected readonly CartRepositoryInterface $cartRepository,
    ) {
    }

    /**
     * Copy data from quote to order
     *
     * @param OrderService $subject
     * @param OrderInterface $result
     * @param OrderInterface $order
     * @return OrderInterface
     * @throws NoSuchEntityException
     */
    public function afterPlace(OrderService $subject, $result, OrderInterface $order): OrderInterface
    {
        $quote = $this->cartRepository->get($order->getQuoteId());

        $order->setData('orlenpaczka_point_details', $quote->getData('orlenpaczka_point_details'));
        $order->setData('orlenpaczka_destination_code', $quote->getData('orlenpaczka_destination_code'));
        $this->orderRepository->save($order);

        return $result;
    }
}
