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

use Chill\DocStoreBundle\GenericDoc\Exception\AssociatedStoredObjectNotFound;
use Chill\DocStoreBundle\GenericDoc\ManagerInterface;
use Chill\MainBundle\Entity\Workflow\EntityWorkflowAttachment;
use Doctrine\ORM\EntityManagerInterface;

class AddAttachmentAction
{
    public function __construct(private readonly EntityManagerInterface $em, private readonly ManagerInterface $manager) {}

    /**
     * @throws AssociatedStoredObjectNotFound
     */
    public function __invoke(AddAttachmentRequestDTO $dto): EntityWorkflowAttachment
    {
        $genericDoc = $this->manager->buildOneGenericDoc($dto->relatedGenericDocKey, $dto->relatedGenericDocIdentifiers);

        if (null === $genericDoc) {
            throw new \RuntimeException(sprintf('could not build any generic doc, %s key and %s identifiers', $dto->relatedGenericDocKey, json_encode($dto->relatedGenericDocIdentifiers)));
        }

        $storedObject = $this->manager->fetchStoredObject($genericDoc);

        $attachement = new EntityWorkflowAttachment($dto->relatedGenericDocKey, $dto->relatedGenericDocIdentifiers, $dto->entityWorkflow, $storedObject);

        $this->em->persist($attachement);

        return $attachement;
    }
}
