<?php

declare(strict_types=1);

/**
 * @author Colinet Julien
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Twig;

use CpCreation\VitiCore\Product\Repository\ProductPriceCodeRepository;
use CpCreation\VitiCore\Product\Repository\ProductPriceGroupRepository;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;

class CookiePriceCodeConvertExtension extends AbstractExtension
{
    public function __construct(
        private ProductPriceGroupRepository $productPriceGroupRepository,
        private ProductPriceCodeRepository $productPriceCodeRepository,
    ) {
    }

    public function getFilters(): array
    {
        return [
            new TwigFilter('convert_id_to_name', [$this, 'convertIdToNameFilter']),
            new TwigFilter('get_ht_or_ttc', [$this, 'getHtOrTTCFilter']),
        ];
    }

    public function convertIdToNameFilter(mixed $id): ?string
    {
        $priceCode = $this->productPriceCodeRepository->find($id);

        return $priceCode?->getCode();
    }

    public function getHtOrTTCFilter(mixed $id): string
    {
        $priceGroup = $this->productPriceGroupRepository->find($id);

        if (null === $priceGroup) {
            return 'TTC';
        }

        return $priceGroup->isViewHT() ? 'HT' : 'TTC';
    }
}
