<?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\Shared\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)]
final class AttachmentsSyncListener
{
    public function __construct(private readonly Security $security)
    {
    }

    public function preFlush(PreFlushEventArgs $args): void
    {
        $em = $args->getObjectManager();
        $uow = $em->getUnitOfWork();

        $attachmentMeta = $em->getClassMetadata(Attachment::class);

        /** @var list<object> $candidates */
        $candidates = array_merge(
            $uow->getScheduledEntityInsertions(),
            $uow->getScheduledEntityUpdates()
        );

        foreach ($candidates as $entity) {
            if (!$entity instanceof AttachmentsInterface) {
                continue;
            }

            $files = $entity->getFiles();

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

                if (UnitOfWork::STATE_NEW !== $uow->getEntityState($file)) {
                    continue;
                }

                $user = $this->security->getUser();

                // owner seulement si pas déjà défini, et si le user n'est pas un Tenant
                if (null === $file->getOwner() && $user instanceof UserInterface && !$user instanceof Tenant) {
                    $file->setOwner($user);
                }

                $em->persist($file);
                $uow->computeChangeSet($attachmentMeta, $file);
            }
        }
    }
}
