<?php

/*
 * 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\EventListener;

use CpCreation\VitiCore\Behavior\HasGroupAvailable;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Context\GroupContext;
use CpCreation\VitiCore\Product\Repository\ProductPriceGroupRepository;
use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;
use Doctrine\ORM\Event\PostLoadEventArgs;
use Doctrine\ORM\Events;

#[AsDoctrineListener(event: Events::postLoad)]
class DoctrineSetCurrentGroupOnPostLoadListener
{
    public function __construct(
        private ProductPriceGroupRepository $groupRepository,
    ) {
    }

    public function postLoad(PostLoadEventArgs $eventArgs): void
    {
        $entity = $eventArgs->getObject();
        if (!$entity instanceof HasGroupAvailable) {
            return;
        }

        $defaultGroup = $this->groupRepository->getGroupByDefault();
        if (!$defaultGroup) {
            throw new \LogicException('Group by default undefined');
        }

        $group = $defaultGroup;
        if (null !== GroupContext::$groupId) {
            $contextGroup = $this->groupRepository->findOneBy([
                'id' => GroupContext::$groupId,
            ]);

            if (null !== $contextGroup) {
                $group = $contextGroup;
            }
        }

        $entity->setGroupAvailable($group);
    }
}
