<?php

declare(strict_types=1);

namespace CpCreation\VitiCore\Bridge\Doctrine\EventSubscriber;

use CpCreation\VitiCore\Cart\Model\Cart;
use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;
use Doctrine\ORM\Events;
use Doctrine\Persistence\Event\LifecycleEventArgs;
use Symfony\Component\HttpFoundation\RequestStack;

#[AsDoctrineListener(event: Events::prePersist)]
#[AsDoctrineListener(event: Events::preUpdate)]
readonly class CartSubscriber
{
    public function __construct(
        private RequestStack $requestStack,
    ) {
    }

    public function prePersist(LifecycleEventArgs $event): void
    {
        $this->syncLocale($event->getObject());
    }

    public function preUpdate(LifecycleEventArgs $event): void
    {
        $this->syncLocale($event->getObject());
    }

    private function syncLocale(object $entity): void
    {
        if (!$entity instanceof Cart) {
            return;
        }

        $request = $this->requestStack->getCurrentRequest() ?? $this->requestStack->getMainRequest();

        if (null === $request) {
            return;
        }

        $entity->setLocale($request->getLocale());
    }
}
