<?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\DocStoreBundle\Tests\Validator\Constraints;

use Chill\DocStoreBundle\Entity\StoredObject;
use Chill\DocStoreBundle\Entity\StoredObjectVersion;
use Chill\DocStoreBundle\Service\StoredObjectManagerInterface;
use Chill\DocStoreBundle\Validator\Constraints\AsyncFileExists;
use Chill\DocStoreBundle\Validator\Constraints\AsyncFileExistsValidator;
use Prophecy\Argument;
use Prophecy\PhpUnit\ProphecyTrait;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;

/**
 * @internal
 *
 * @coversNothing
 */
class AsyncFileExistsValidatorTest extends ConstraintValidatorTestCase
{
    use ProphecyTrait;

    protected function createValidator()
    {
        $storedObjectManager = $this->prophesize(StoredObjectManagerInterface::class);
        $storedObjectManager->exists(Argument::any())
            ->will(function ($args): bool {
                /** @var StoredObject|StoredObjectVersion $arg0 */
                $arg0 = $args[0];

                if ($arg0 instanceof StoredObjectVersion) {
                    $storedObject = $arg0->getStoredObject();
                } else {
                    $storedObject = $arg0;
                }

                if ('present' === $storedObject->getCurrentVersion()->getFilename()) {
                    return true;
                }

                return false;
            });

        return new AsyncFileExistsValidator($storedObjectManager->reveal());
    }

    public function testWhenFileExistsIsValid(): void
    {
        $object = new StoredObject();
        $object->registerVersion(filename: 'present');
        $this->validator->validate($object, new AsyncFileExists());

        $this->assertNoViolation();
    }

    public function testWhenFileIsNotPresent(): void
    {
        $object = new StoredObject();
        $object->registerVersion(filename: 'absent');

        $this->validator->validate(
            $object,
            new AsyncFileExists(['message' => 'my_message'])
        );

        $this->buildViolation('my_message')->setParameter('{{ filename }}', 'absent')->assertRaised();
    }
}
