<?php

declare(strict_types=1);

namespace Macopedia\OrlenShipping\Plugin;

use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\Data\OrderSearchResultInterface;
use Magento\Sales\Model\OrderRepository;

class OrderRepositoryPlugin
{
    /**
     * Copy data from extension attributes
     *
     * @param OrderRepository $subject
     * @param OrderInterface $order
     * @return void
     */
    public function beforeSave(
        OrderRepository $subject,
        OrderInterface $order
    ): void {
        $extensionAttributes = $order->getExtensionAttributes();
        if ($extensionAttributes !== null
            && $extensionAttributes->getOrlenpaczkaPointDetails()
            && $extensionAttributes->getOrlenpaczkaDestinationCode()
        ) {
            $order->setData('orlenpaczka_point_details', $extensionAttributes->getOrlenpaczkaPointDetails());
            $order->setData('orlenpaczka_destination_code', $extensionAttributes->getOrlenpaczkaDestinationCode());
        }
    }

    /**
     * Set extension attributes
     *
     * @param OrderRepository $subject
     * @param OrderInterface $order
     * @return OrderInterface
     */
    public function afterGet(
        OrderRepository $subject,
        OrderInterface $order
    ): OrderInterface {
        $extensionAttributes = $order->getExtensionAttributes();
        $extensionAttributes->setOrlenpaczkaPointDetails($order->getData('orlenpaczka_point_details'));
        $extensionAttributes->setOrlenpaczkaDestinationCode($order->getData('orlenpaczka_destination_code'));
        $order->setExtensionAttributes($extensionAttributes);

        return $order;
    }

    /**
     * Set extension attributes
     *
     * @param OrderRepository $subject
     * @param OrderSearchResultInterface $searchResult
     * @return OrderSearchResultInterface
     */
    public function afterGetList(
        OrderRepository $subject,
        OrderSearchResultInterface $searchResult
    ): OrderSearchResultInterface {
        foreach ($searchResult->getItems() as $order) {
            $extensionAttributes = $order->getExtensionAttributes();
            $extensionAttributes->setOrlenpaczkaPointDetails($order->getData('orlenpaczka_point_details'));
            $extensionAttributes->setOrlenpaczkaDestinationCode($order->getData('orlenpaczka_destination_code'));
            $order->setExtensionAttributes($extensionAttributes);
        }

        return $searchResult;
    }
}
