<?php

namespace KupShop\GraphQLBundle\ApiPos\Types\Order;

use KupShop\GraphQLBundle\ApiAdmin\Types\Order\Order;
use KupShop\GraphQLBundle\ApiPos\Types\Collection\PosOrderPaymentsCollection;
use KupShop\GraphQLBundle\ApiPos\Types\User\User;
use KupShop\GraphQLBundle\ApiPos\Types\Warehouse\PosOrderWarehouse;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\OrderingBundle\OrderList\OrderCollection;
use KupShop\POSBundle\Util\PosEntity;
use KupShop\POSBundle\Util\PosStoreUtil;
use KupShop\POSBundle\Util\PosWarehouseUtil;
use TheCodingMachine\GraphQLite\Annotations\Field;
use TheCodingMachine\GraphQLite\Annotations\Type;

#[Type]
class PosOrder extends Order
{
    public PosStoreUtil $posStoreUtil;
    public PosWarehouseUtil $posWarehouseUtil;

    protected PosEntity $posEntity;
    protected $warehouse;
    protected ?PosOrderPaymentsCollection $payments;

    public function __construct(\Order $order, PosEntity $posEntity, $warehouse = null, ?PosOrderPaymentsCollection $payments = null, ?OrderCollection $collection = null)
    {
        parent::__construct($order, $collection);
        $this->posStoreUtil = ServiceContainer::getService(PosStoreUtil::class);
        $this->posWarehouseUtil = ServiceContainer::getService(PosWarehouseUtil::class);
        $this->warehouse = $warehouse;
        $this->posEntity = $posEntity;
        $this->payments = $payments;
    }

    #[Field(description: 'Status vyřízení')]
    public function getIsHandled(): bool
    {
        return in_array($this->order->status, getStatuses('handled'));
    }

    #[Field(outputType: '[PosOrderItem!]!', prefetchMethod: 'prefetchItems', description: 'Položky objednávky')]
    public function getItems(array $_ = []): array
    {
        $result = [];
        foreach ($this->order->fetchItems() as $item) {
            if (is_array($item)) {
                $item = new \KupShop\OrderingBundle\Entity\Order\OrderItem($item);
            }

            if ($item->getProduct()) {
                $stores = $this->posStoreUtil->getStoresCollection($item->getProduct());
                $warehouse = $this->posWarehouseUtil->getWarehouseItem($this->posEntity, $item->getProduct());
            }

            $result[] = new PosOrderItem($item, $stores ?? null, $warehouse ?? null, $this->collection);
        }

        return $result;
    }

    #[Field(prefetchMethod: 'prefetchUsers', description: 'Uživatel.')]
    public function getOrderUser(array $users): ?User
    {
        if (!($users[$this->order->id_user] ?? false)) {
            return null;
        }

        return new User($users[$this->order->id_user]);
    }

    #[Field(description: 'Informace o vychystané objednávce')]
    public function getWarehouse(): ?PosOrderWarehouse
    {
        return $this->warehouse;
    }

    #[Field(description: 'Seznam všech plateb u objednávky')]
    public function getPayments(): ?PosOrderPaymentsCollection
    {
        return $this->payments;
    }
}
