<?php

use PHPUnit\Framework\TestCase;
use Symfony\Bridge\Twig\Extension\FormExtension;
use Symfony\Bridge\Twig\Extension\TranslationExtension;
use Symfony\Component\Translation\Translator;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;
use Twig\TwigFunction;

final class DeliveryMethodCategoryDescriptionTest extends TestCase
{
    public function testCategoryDescriptionIsRenderedUnderCategoryTitle(): void
    {
        $html = $this->renderDeliveryMethodWidget();

        self::assertStringContainsString('<h4 class="shop">Retrait domaine</h4>', $html);
        self::assertStringContainsString('Description visible de la categorie livraison', $html);
        self::assertMatchesRegularExpression(
            '#<h4 class="shop">Retrait domaine</h4>\s*<div class="deliveryMethod_description deliveryMethod_category_description">Description visible de la categorie livraison</div>#',
            $html
        );
    }

    private function renderDeliveryMethodWidget(): string
    {
        $translator = new Translator('fr');
        $loader = new FilesystemLoader(__DIR__ . '/../../Resources/views/form');
        $twig = new Environment($loader);
        $twig->addExtension(new FormExtension($translator));
        $twig->addExtension(new TranslationExtension($translator));
        $twig->addFunction(new TwigFunction('path', static function (): string {
            return '#';
        }));

        $template = $twig->load('fields.html.twig');
        $category = (object) [
            'name' => 'Retrait domaine',
            'description' => 'Description visible de la categorie livraison',
            'minView' => false,
            'minViewTextOpen' => null,
            'minViewTextClose' => null,
        ];
        $method = (object) [
            'id' => 'method-1',
            'category' => $category,
            'counties' => [],
            'qtyAt' => null,
            'packagePrice' => 0,
            'bottlePrice' => null,
            'viewCounties' => false,
            'description' => null,
            'enabledShippingPrice' => false,
            'otherText' => null,
        ];
        $choice = (object) [
            'data' => $method,
            'label' => 'Retrait sur place',
            'value' => 'method-1',
        ];

        return $template->renderBlock('_cart_deliveryMethod_widget', [
            'form' => ['vars' => ['choices' => [$choice], 'data' => null]],
            'choices' => [$choice],
            'config' => (object) ['otherDeliveryMethodColor' => null],
            'required' => false,
            'disabled' => false,
            'label' => 'delivery',
            'label_attr' => [],
            'label_format' => null,
            'name' => 'deliveryMethod',
            'id' => 'cart_deliveryMethod',
            'full_name' => 'cart[deliveryMethod]',
        ]);
    }
}
