<?php

declare(strict_types=1);

namespace KupShop\GraphQLBundle\ApiAdmin\Types\Purchase;

use KupShop\GraphQLBundle\ApiShared\Types\Price\Price;
use KupShop\GraphQLBundle\ApiShared\Types\Product\Product;
use KupShop\OrderingBundle\Util\Purchase\PurchaseItemUtil;
use TheCodingMachine\GraphQLite\Annotations\Autowire;
use TheCodingMachine\GraphQLite\Annotations\Field;
use TheCodingMachine\GraphQLite\Annotations\Type;

#[Type]
class ProductPurchaseItem
{
    public function __construct(
        private \KupShop\OrderingBundle\Entity\Purchase\ProductPurchaseItem $purchaseItem,
    ) {
    }

    #[Field(description: 'ID produktu.')]
    public function getProductId(): int
    {
        return (int) $this->purchaseItem->getIdProduct();
    }

    #[Field(description: 'ID varianty.')]
    public function getVariationId(): ?int
    {
        return $this->purchaseItem->getIdVariation() ? (int) $this->purchaseItem->getIdVariation() : null;
    }

    #[Field(description: 'Název.')]
    public function getName(): string
    {
        return $this->purchaseItem->getName();
    }

    #[Field(description: 'Počet kusů.')]
    public function getPieces(): float
    {
        return (float) $this->purchaseItem->getPieces();
    }

    #[Field(description: 'Jednotková cena.')]
    public function getPiecePrice(): Price
    {
        return new Price($this->purchaseItem->getPiecePrice());
    }

    #[Field(description: 'Celková cena.')]
    public function getTotalPrice(): Price
    {
        return new Price($this->purchaseItem->getPrice());
    }

    /**
     * @return ProductPurchaseItemDiscount[]
     */
    #[Field(description: 'Uplatněné slevy na produktu.')]
    public function getDiscounts(): array
    {
        $result = [];

        foreach ($this->purchaseItem->getDiscounts() as $discount) {
            $discount['vat'] = $this->purchaseItem->getPrice()->getVat();
            $result[] = new ProductPurchaseItemDiscount($discount);
        }

        return $result;
    }

    #[Field(description: 'Produkt.')]
    public function getProduct(): Product
    {
        return new Product(
            $this->purchaseItem->getProduct(),
            $this->purchaseItem->getPurchaseState()->createProductCollection()
        );
    }

    #[Field(description: 'Cena před slevami.')]
    public function getProductOriginalPrice(#[Autowire] PurchaseItemUtil $purchaseItemUtil): Price
    {
        $priceOriginal = $purchaseItemUtil->getProductItemOriginalPrice($this->purchaseItem);

        return new Price(
            $priceOriginal, false
        );
    }

    #[Field(description: 'Sleva na produktu.')]
    public function getDiscount(#[Autowire] PurchaseItemUtil $purchaseItemUtil): float
    {
        return $purchaseItemUtil->getProductItemDiscount($this->purchaseItem)->asFloat();
    }
}
