<?php

declare(strict_types=1);

namespace External\PompoBundle\Overrides\GraphQL\Types\Extension;

use External\PompoBundle\Overrides\GraphQL\Types\PompoDiscountCodeValue;
use External\PompoBundle\Util\Api\ApiUtil;
use KupShop\GraphQLBundle\ApiAdmin\Types\OrderDiscount\DiscountCoupon;
use KupShop\KupShopBundle\Context\CurrencyContext;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\KupShopBundle\Util\Contexts;
use TheCodingMachine\GraphQLite\Annotations\ExtendType;
use TheCodingMachine\GraphQLite\Annotations\Field;

#[ExtendType(class: DiscountCoupon::class)]
class DiscountCouponExtension
{
    #[Field(description: 'Hodnota poukazu. Pokud poukaz už není možné uplatnit, tak je vraceno `null`.')]
    public function getPompoValue(DiscountCoupon $discountCoupon): ?PompoDiscountCodeValue
    {
        $data = $this->getApiUtil()->useVoucher(['number' => $discountCoupon->getCode()], true);

        $value = $data['voucher']['value'] ?? null;
        $type = ($data['voucher']['template']['valueType'] ?? null) === 1 ? 'perc' : Contexts::get(CurrencyContext::class)->getActiveId();

        if ($value) {
            return new PompoDiscountCodeValue((float) $value, (string) $type);
        }

        return null;
    }

    private function getApiUtil(): ApiUtil
    {
        static $apiUtil;

        if (null === $apiUtil) {
            $apiUtil = ServiceContainer::getService(ApiUtil::class);
        }

        return $apiUtil;
    }
}
