<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Tests\Phonenumber;

use Chill\MainBundle\Phonenumber\PhonenumberHelper;
use libphonenumber\PhoneNumber;
use libphonenumber\PhoneNumberUtil;
use Psr\Log\NullLogger;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;

/**
 * @internal
 *
 * @coversNothing
 */
final class PhonenumberHelperTest extends KernelTestCase
{
    /**
     * @dataProvider formatPhonenumbers
     */
    public function testFormatPhonenumbers(string $defaultCarrierCode, string $phoneNumber, string $expected)
    {
        $util = PhoneNumberUtil::getInstance();

        $subject = new PhonenumberHelper(
            new ArrayAdapter(),
            new ParameterBag([
                'chill_main.phone_helper' => [
                    'default_carrier_code' => $defaultCarrierCode,
                ],
            ]),
            new NullLogger()
        );

        $this->assertEquals($expected, $subject->format($util->parse($phoneNumber)));
    }

    public static function formatPhonenumbers()
    {
        yield [
            'BE',
            '+3281136917',
            '081 13 69 17',
        ];

        yield [
            'FR',
            '+33 6 23 12 45 54',
            '06 23 12 45 54',
        ];

        yield [
            'FR',
            '+32 81 13 69 17',
            '00 32 81 13 69 17',
        ];

        yield [
            'BE',
            '+33 6 23 12 45 54',
            '00 33 6 23 12 45 54',
        ];
    }

    /**
     * @dataProvider providePhoneNumbersToParse
     */
    public function testParsePhonenumbers(string $defaultCarrierCode, string $phoneNumber, PhoneNumber $expected): void
    {
        $subject = new PhonenumberHelper(
            new ArrayAdapter(),
            new ParameterBag([
                'chill_main.phone_helper' => [
                    'default_carrier_code' => $defaultCarrierCode,
                ],
            ]),
            new NullLogger()
        );

        $actual = $subject->parse($phoneNumber);

        self::assertTrue($expected->equals($actual));
    }

    public static function providePhoneNumbersToParse(): iterable
    {
        $util = PhoneNumberUtil::getInstance();

        yield [
            'FR',
            '+32486544999',
            $util->parse('+32486544999', 'FR'),
        ];

        yield [
            'FR',
            '32486544999',
            $util->parse('+32486544999', 'FR'),
        ];

        yield [
            'FR',
            '0228858040',
            $util->parse('+33228858040', 'FR'),
        ];
    }
}
