<?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\Export\Messenger;

use Chill\DocStoreBundle\Entity\StoredObject;
use Chill\MainBundle\Entity\ExportGeneration;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Export\Exception\ExportGenerationException;
use Chill\MainBundle\Export\Messenger\ExportRequestGenerationMessage;
use Chill\MainBundle\Export\Messenger\OnExportGenerationFails;
use Chill\MainBundle\Repository\ExportGenerationRepository;
use Doctrine\ORM\EntityManagerInterface;
use PHPUnit\Framework\TestCase;
use Prophecy\PhpUnit\ProphecyTrait;
use Psr\Log\NullLogger;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\Event\WorkerMessageFailedEvent;

/**
 * @internal
 *
 * @coversNothing
 */
class OnExportGenerationFailsTest extends TestCase
{
    use ProphecyTrait;

    public function testOnExportGenerationFails(): void
    {
        $exportGeneration = new ExportGeneration('dummy');
        $exportGeneration->setCreatedAt(new \DateTimeImmutable('10 seconds ago'));

        $repository = $this->prophesize(ExportGenerationRepository::class);
        $repository->find($exportGeneration->getId())->willReturn($exportGeneration);

        $entityManager = $this->prophesize(EntityManagerInterface::class);
        $entityManager->flush()->shouldBeCalled();

        $user = $this->prophesize(User::class);
        $user->getId()->willReturn(1);

        $subscriber = new OnExportGenerationFails(new NullLogger(), $repository->reveal(), $entityManager->reveal());

        $subscriber->onMessageFailed(new WorkerMessageFailedEvent(
            new Envelope(new ExportRequestGenerationMessage($exportGeneration, $user->reveal())),
            'dummyReceiver',
            new ExportGenerationException('dummy_exception'),
        ));

        self::assertEquals(StoredObject::STATUS_FAILURE, $exportGeneration->getStoredObject()->getStatus());
        self::assertStringContainsString('dummy_exception', $exportGeneration->getStoredObject()->getGenerationErrors());
    }
}
