<?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\Workflow\Attachment;

use Chill\DocStoreBundle\Entity\StoredObject;
use Chill\DocStoreBundle\GenericDoc\GenericDocDTO;
use Chill\DocStoreBundle\GenericDoc\ManagerInterface;
use Chill\MainBundle\Entity\Workflow\EntityWorkflow;
use Chill\MainBundle\Entity\Workflow\EntityWorkflowAttachment;
use Chill\MainBundle\Workflow\Attachment\AddAttachmentAction;
use Chill\MainBundle\Workflow\Attachment\AddAttachmentRequestDTO;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Doctrine\ORM\EntityManagerInterface;
use PHPUnit\Framework\TestCase;

/**
 * @internal
 *
 * @coversNothing
 */
class AddAttachmentActionTest extends TestCase
{
    private EntityManagerInterface $entityManagerMock;
    private AddAttachmentAction $addAttachmentAction;

    private ManagerInterface $manager;

    protected function setUp(): void
    {
        $this->entityManagerMock = $this->createMock(EntityManagerInterface::class);
        $this->manager = $this->createMock(ManagerInterface::class);
        $this->addAttachmentAction = new AddAttachmentAction($this->entityManagerMock, $this->manager);
    }

    public function testInvokeCreatesAndPersistsEntityWorkflowAttachment(): void
    {
        $entityWorkflow = new EntityWorkflow();
        $dto = new AddAttachmentRequestDTO($entityWorkflow);
        $dto->relatedGenericDocKey = 'doc_key';
        $dto->relatedGenericDocIdentifiers = ['id' => 1];
        $this->manager->method('buildOneGenericDoc')->willReturn($g = new GenericDocDTO('doc_key', ['id' => 1], new \DateTimeImmutable(), new AccompanyingPeriod()));
        $this->manager->method('fetchStoredObject')->with($g)->willReturn($storedObject = new StoredObject());

        $this->entityManagerMock
            ->expects($this->once())
            ->method('persist')
            ->with($this->isInstanceOf(EntityWorkflowAttachment::class));

        $result = $this->addAttachmentAction->__invoke($dto);

        $this->assertInstanceOf(EntityWorkflowAttachment::class, $result);
        $this->assertSame('doc_key', $result->getRelatedGenericDocKey());
        $this->assertSame(['id' => 1], $result->getRelatedGenericDocIdentifiers());
        $this->assertSame($entityWorkflow, $result->getEntityWorkflow());
        $this->assertSame($storedObject, $result->getProxyStoredObject());
    }
}
