<?php

declare(strict_types=1);

namespace KupShop\GraphQLBundle\ApiAdmin\Types\Sale;

use KupShop\GraphQLBundle\ApiAdmin\Types\Order\DeliveryType\DeliveryType;
use KupShop\GraphQLBundle\ApiAdmin\Types\User\User;
use KupShop\GraphQLBundle\ApiShared\ApiUtil;
use KupShop\GraphQLBundle\ApiShared\Types\Language;
use KupShop\GraphQLBundle\ApiShared\Types\Price\Currency;
use KupShop\GraphQLBundle\ApiShared\Types\Price\TotalPrice;
use KupShop\I18nBundle\Context\CurrencyContext;
use KupShop\KupShopBundle\Util\Contexts;
use KupShop\SalesBundle\SaleList\SaleCollection;
use TheCodingMachine\GraphQLite\Annotations\Field;
use TheCodingMachine\GraphQLite\Annotations\Type;

#[Type]
class Sale
{
    public function __construct(
        private readonly \KupShop\SalesBundle\Entity\Sale $sale,
        public SaleCollection $saleCollection,
    ) {
    }

    #[Field(description: 'ID')]
    public function getId(): int
    {
        return $this->sale->id;
    }

    #[Field(description: 'Kód')]
    public function getCode(): string
    {
        return $this->sale->code;
    }

    #[Field(description: 'Měna')]
    public function getCurrency(): Currency
    {
        return ApiUtil::prepareCurrency(
            $this->sale->currency ?: Contexts::get(CurrencyContext::class)->getDefaultId()
        );
    }

    #[Field(description: 'Jazyk')]
    public function getLanguage(): Language
    {
        return ApiUtil::prepareLanguage(
            $this->sale->languageId ?: 'cs'
        );
    }

    #[Field(description: 'Datum vytvoření')]
    public function getDateCreated(): \DateTimeInterface
    {
        return ApiUtil::prepareDateTimeFromDB($this->sale->dateCreated);
    }

    #[Field(description: 'Uživatel')]
    public function getUser(): ?User
    {
        if (!$this->sale->userId) {
            return null;
        }

        return new User(
            $this->sale->getUser()
        );
    }

    #[Field(description: 'Způsob doručení')]
    public function getDeliveryType(): ?DeliveryType
    {
        if ($this->sale->getDeliveryType()) {
            return new DeliveryType(
                $this->sale->getDeliveryType()
            );
        }

        return null;
    }

    #[Field(description: 'Poznámka')]
    public function getNote(): ?string
    {
        return $this->sale->note;
    }

    #[Field(description: 'Celková cena')]
    public function getTotalPrice(): TotalPrice
    {
        return new TotalPrice(
            $this->sale->totalPrice
        );
    }

    #[Field(description: 'JSON data')]
    public function getData(): string
    {
        return json_encode($this->sale->data);
    }

    /**
     * @return SaleItem[]
     */
    #[Field(description: 'Položky')]
    public function getItems(): array
    {
        $items = [];

        foreach ($this->sale->items as $item) {
            $items[] = new SaleItem($item, $this->saleCollection);
        }

        return $items;
    }
}
