<?php

declare(strict_types=1);

namespace CpCreation\VitiCore\Tests\Form\Admin;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Admin\FileType;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Admin\ShippingConfigType;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

final class ShippingConfigTypeTest extends TestCase
{
    public function testConfiguredCarriersAreExposedAsFormChoices(): void
    {
        $authorizationChecker = $this->createMock(AuthorizationCheckerInterface::class);
        $authorizationChecker->expects(self::once())
            ->method('isGranted')
            ->with('ROLE_ADMIN')
            ->willReturn(true);

        $carrierType = null;
        $carrierOptions = null;
        $builder = $this->createMock(FormBuilderInterface::class);
        $builder->method('add')
            ->willReturnCallback(
                static function (mixed $child, ?string $type = null, array $options = []) use (&$carrierType, &$carrierOptions, $builder): FormBuilderInterface {
                    if ('carrier' === $child) {
                        $carrierType = $type;
                        $carrierOptions = $options;
                    }

                    return $builder;
                }
            );

        new ShippingConfigType($authorizationChecker, ['transvins', 'geodis'])
            ->buildForm($builder, []);

        self::assertSame(ChoiceType::class, $carrierType);
        self::assertIsArray($carrierOptions);
        self::assertSame([
            'transvins' => 'transvins',
            'geodis' => 'geodis',
        ], $carrierOptions['choices']);
    }

    public function testCarrierFilesUseTheMediaFileFormType(): void
    {
        $authorizationChecker = $this->createMock(AuthorizationCheckerInterface::class);
        $authorizationChecker->expects(self::once())
            ->method('isGranted')
            ->with('ROLE_ADMIN')
            ->willReturn(true);

        $fileTypes = [];
        $builder = $this->createMock(FormBuilderInterface::class);
        $builder->method('add')
            ->willReturnCallback(
                static function (mixed $child, ?string $type = null) use (&$fileTypes, $builder): FormBuilderInterface {
                    if (\in_array($child, ['file', 'fileSup'], true)) {
                        $fileTypes[$child] = $type;
                    }

                    return $builder;
                }
            );

        new ShippingConfigType($authorizationChecker)
            ->buildForm($builder, []);

        self::assertSame([
            'file' => FileType::class,
            'fileSup' => FileType::class,
        ], $fileTypes);
    }
}
