<?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 CpCreation\VitiCore\Bridge\Doctrine\EventSubscriber;

use CpCreation\VitiCore\Cart\Model\PaymentMethod;
use CpCreation\VitiCore\Cart\Repository\CartRepository;
use CpCreation\VitiCore\Payment\Model\Payment;
use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;
use Doctrine\ORM\Events;
use Doctrine\Persistence\Event\LifecycleEventArgs;

#[AsDoctrineListener(event: Events::prePersist)]
#[AsDoctrineListener(event: Events::preUpdate)]
readonly class PaymentSubscriber
{
    public function __construct(private CartRepository $cartRepository)
    {
    }

    public function prePersist(LifecycleEventArgs $event): void
    {
        $entity = $event->getObject();
        $entityManager = $event->getObjectManager();
        if ($entity instanceof Payment) {
            $paymentMethod = $entityManager->getRepository(PaymentMethod::class)->findByDefaultForPaymentOnline();
            $cartExistToken = $this->cartRepository->findOneBy(['token' => $entity->getReference()]);
            if ($cartExistToken) {
                $entity->setReference($entity->getReference().'-1');
            }
            $entity->setPaymentMethod($paymentMethod);
        }
    }

    public function preUpdate(LifecycleEventArgs $event): void
    {
        $entity = $event->getObject();
        $entityManager = $event->getObjectManager();
        if ($entity instanceof Payment) {
            $paymentMethod = $entityManager->getRepository(PaymentMethod::class)->findByDefaultForPaymentOnline();
            $entity->setPaymentMethod($paymentMethod);
            $cartExistToken = $this->cartRepository->findOneBy(['token' => $entity->getReference()]);
            if ($cartExistToken) {
                $entity->setReference($entity->getReference().'-1');
            }
        }
    }
}
