<?php

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Serenity\MediaBundle\Doctrine\Listener;

use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;
use Doctrine\ORM\Event\PreFlushEventArgs;
use Doctrine\ORM\Events;
use Doctrine\ORM\UnitOfWork;
use Serenity\CoreBundle\Domain\Common\UserInterface;
use Serenity\MediaBundle\Contract\AttachmentsInterface;
use Serenity\MediaBundle\Entity\Attachment;
use Serenity\SaasBundle\Entity\Tenant;
use Symfony\Bundle\SecurityBundle\Security;

#[AsDoctrineListener(event: Events::preFlush)]
class AttachmentsSyncListener
{
    public function __construct(private Security $security)
    {
    }

    public function preFlush(PreFlushEventArgs $args): void
    {
        $em = $args->getObjectManager();
        $uow = $em->getUnitOfWork();
        $attachmentMeta = $em->getClassMetadata(Attachment::class);
        $candidates = array_merge(
            $uow->getScheduledEntityInsertions(),
            $uow->getScheduledEntityUpdates()
        );
        foreach ($uow->getIdentityMap() as $class => $entities) {
            foreach ($entities as $entity) {
                if (!$entity instanceof AttachmentsInterface) {
                    continue;
                }

                // Récupère la collection "files" depuis l'interface
                $files = $entity->getFiles();
                if (0 === \count($files)) {
                    continue;
                }

                foreach ($files as $file) {
                    if (!$file instanceof Attachment) {
                        continue;
                    }

                    $state = $uow->getEntityState($file);

                    // Persist uniquement si l'état est NEW
                    if (UnitOfWork::STATE_NEW === $state) {
                        $user = $this->security->getUser();
                        /** @var UserInterface $user */
                        $user = $this->security->getUser();
                        if (null === $file->getOwner() && !$user instanceof Tenant) {
                            $file->setOwner($user);
                        }
                        $em->persist($file);
                        $uow->computeChangeSet($attachmentMeta, $file);
                    }
                }
            }
        }
    }
}
