<?php

declare(strict_types=1);

/*
 * This file is part of the VITICORE2 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 CpCreation\VitiCore\Bridge\Doctrine\EventSubscriber;

use CpCreation\VitiCore\Commerce\Catalog\Enrollment\Model\CatalogEnrollmentRequest;
use CpCreation\VitiCore\Commerce\Catalog\Model\CatalogConfiguration;
use CpCreation\VitiCore\Product\Model\ProductCategory;
use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\ORM\Events;

/**
 * Transforme l'activation du premier export en signal transactionnel durable.
 * Le payload et son fingerprint sont préparés plus tard, hors du flush métier.
 */
#[AsDoctrineListener(event: Events::onFlush)]
final class CatalogEnrollmentSubscriber
{
    public function onFlush(OnFlushEventArgs $event): void
    {
        $entityManager = $event->getObjectManager();
        if (!$entityManager instanceof EntityManagerInterface) {
            return;
        }

        $unitOfWork = $entityManager->getUnitOfWork();
        $requested = false;

        foreach ($unitOfWork->getScheduledEntityInsertions() as $entity) {
            if (($entity instanceof ProductCategory && $entity->isCommerceExportEnabled())
                || ($entity instanceof CatalogConfiguration && $entity->isEnabled())
            ) {
                $requested = true;
                break;
            }
        }

        if (!$requested) {
            foreach ($unitOfWork->getScheduledEntityUpdates() as $entity) {
                $field = match (true) {
                    $entity instanceof ProductCategory => 'commerceExportEnabled',
                    $entity instanceof CatalogConfiguration => 'enabled',
                    default => null,
                };
                if (null === $field) {
                    continue;
                }

                $change = $unitOfWork->getEntityChangeSet($entity)[$field] ?? null;
                if (\is_array($change) && false === $change[0] && true === $change[1]) {
                    $requested = true;
                    break;
                }
            }
        }

        if (!$requested) {
            return;
        }

        $request = new CatalogEnrollmentRequest();
        $entityManager->persist($request);
        $unitOfWork->computeChangeSet(
            $entityManager->getClassMetadata(CatalogEnrollmentRequest::class),
            $request,
        );
    }

}
