<?php

declare(strict_types=1);

namespace KupShop\GraphQLBundle\ApiPublic\Types\Search;

use KupShop\I18nBundle\Util\PriceConverter;
use KupShop\KupShopBundle\Context\CurrencyContext;
use TheCodingMachine\GraphQLite\Annotations\Field;
use TheCodingMachine\GraphQLite\Annotations\Type;

/**
 * @Type()
 */
class AutocompleteProductResultItem extends AutocompleteResultItem
{
    public function __construct(
        protected string $type,
        protected array $item,
        protected string $photoPlaceholder,
        protected CurrencyContext $currencyContext,
        protected PriceConverter $priceConverter,
    ) {
        parent::__construct($type, $item, $photoPlaceholder);
    }

    #[Field]
    public function getDiscount(): int
    {
        return (int) $this->item['sort_discount'];
    }

    #[Field]
    public function getPrice(): string
    {
        if ($this->currencyContext->getDefaultId() != $this->currencyContext->getActiveId()) {
            return printPrice($this->priceConverter->convertPrice(
                fromCurrency: $this->currencyContext->getDefault(),
                toCurrency: $this->currencyContext->getActive(),
                price: toDecimal($this->item['price']),
            )->asFloat());
        }

        return printPrice($this->item['price']);
    }

    #[Field]
    public function getPriceOriginal(): string
    {
        if (!$this->item['price_original']) {
            return '';
        }

        return printPrice($this->item['price_original']);
    }

    #[Field]
    public function getPhoto(): string
    {
        if ($photo = (getImage($this->item['id_photo'], '', '', 2)['src'] ?? false)) {
            return $photo;
        }

        return $this->photoPlaceholder ?? '';
    }

    #[Field]
    public function getDeliveryTimeText(): string
    {
        return $this->item['delivery_time_text'];
    }

    #[Field]
    public function getDeliveryTimeIndex(): int
    {
        return (int) $this->item['delivery_time_index'];
    }
}
