<?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 ChillDocStoreBundle\Tests\Serializer\Normalizer;

use Chill\DocStoreBundle\Entity\StoredObject;
use Chill\DocStoreBundle\Serializer\Normalizer\StoredObjectVersionNormalizer;
use Chill\MainBundle\Serializer\Normalizer\UserNormalizer;
use Chill\MainBundle\Templating\Entity\UserRender;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Clock\MockClock;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\Serializer;

/**
 * @internal
 *
 * @coversNothing
 */
class StoredObjectVersionNormalizerTest extends TestCase
{
    private NormalizerInterface $normalizer;

    protected function setUp(): void
    {
        $userRender = $this->createMock(UserRender::class);
        $userRender->method('renderString')->willReturn('user');
        $this->normalizer = new StoredObjectVersionNormalizer();
        $this->normalizer->setNormalizer(new Serializer([new UserNormalizer($userRender, new MockClock())]));
    }

    public function testNormalize(): void
    {
        $storedObject = new StoredObject();
        $version = $storedObject->registerVersion(
            iv: [1, 2, 3, 4],
            keyInfos: ['someKey' => 'someKey'],
            type: 'text/text',
        );
        $reflection = new \ReflectionClass($version);
        $idProperty = $reflection->getProperty('id');
        $idProperty->setValue($version, 1);

        $actual = $this->normalizer->normalize($version, 'json', ['groups' => ['read']]);

        self::assertEqualsCanonicalizing(
            [
                'id' => 1,
                'version' => 0,
                'filename' => $version->getFilename(),
                'iv' => [1, 2, 3, 4],
                'keyInfos' => ['someKey' => 'someKey'],
                'type' => 'text/text',
                'createdAt' => null,
                'createdBy' => null,
            ],
            $actual
        );
    }

    public function testNormalizeUnsupportedObject(): void
    {
        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessage('The object must be an instance of Chill\DocStoreBundle\Entity\StoredObjectVersion');

        $unsupportedObject = new \stdClass();

        $this->normalizer->normalize($unsupportedObject, 'json', ['groups' => ['read']]);
    }
}
