<?php

declare(strict_types=1);

namespace KupShop\ComponentsBundle\Twig\DataProvider;

use KupShop\ComponentsBundle\Contracts\OrderInterface;
use KupShop\ComponentsBundle\Dto\OrderWrapper;
use KupShop\OrderingBundle\Util\Order\OrderInfo;
use KupShop\OrderingBundle\Util\Order\OrderItemInfo;

class OrderDataProvider
{
    /** @var OrderInterface[] */
    protected array $orders = [];

    public function __construct(
        protected readonly OrderInfo $orderInfo,
        protected readonly OrderItemInfo $orderItemInfo,
    ) {
    }

    public function getOrder(string|int $id): OrderInterface
    {
        return $this->orders[$id] ??= new OrderWrapper(
            $this->createOrder($id),
            $this->orderInfo,
            $this->orderItemInfo,
        );
    }

    protected function createOrder(int $id_order): \Order
    {
        $order = new \Order($id_order);
        $order->createFromDB();

        return $order;
    }

    public function addOrder(\Order|OrderInterface $order): void
    {
        if ($order instanceof \Order) {
            $order = new OrderWrapper($order, $this->orderInfo, $this->orderItemInfo);
        }

        $this->orders[$order->getId()] = $order;
    }

    /**
     * @return array<OrderInterface|\Order>
     */
    public function addOrders(array $orders): array
    {
        foreach ($orders as $order) {
            $this->addOrder($order);
        }

        return $orders;
    }
}
