<?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\Product\Repository;

use CpCreation\VitiCore\Product\Model\ProductPriceGroup;
use CpCreation\VitiCore\Repository\BaseRepository;
use CpCreation\VitiCore\User\Model\User;
use Doctrine\Persistence\ManagerRegistry;

class ProductPriceGroupRepository extends BaseRepository
{
    private bool $defaultGroupLoaded = false;

    private ?ProductPriceGroup $defaultGroup = null;

    /**
     * @throws \ReflectionException
     */
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, ProductPriceGroup::class);
    }

    /**
     * @return ProductPriceGroup[]
     */
    public function findNotSoftDeletable(): array
    {
        $qb = $this->createQueryBuilder('pg');

        $qb
            ->leftJoin('pg.codes', 'c')
            ->andWhere(
                $qb->expr()->orX(
                    $qb->expr()->eq('pg.byDefault', ':default'),
                    $qb->expr()->andX(
                        $qb->expr()->isNull('c.deletedAt'),
                        $qb->expr()->neq('c.disabled', ':disabled')
                    )
                )
            )
            ->setParameter('default', true)
            ->setParameter('disabled', true);

        return $qb->getQuery()->getResult();
    }

    public function getGroupByDefault(): ?ProductPriceGroup
    {
        if ($this->defaultGroupLoaded) {
            return $this->defaultGroup;
        }

        $this->defaultGroupLoaded = true;

        $qb = $this->createQueryBuilder('g')
            ->andWhere('g.byDefault = TRUE')
            ->setMaxResults(1);

        return $this->defaultGroup = $qb->getQuery()->getOneOrNullResult();
    }

    public function deleteGroup(ProductPriceGroup $group): void
    {
        $entityManager = $this->getEntityManager();

        foreach ($entityManager->getRepository(User::class)->findBy(['group' => $group]) as $user) {
            if (!$user instanceof User) {
                continue;
            }

            $user->setGroup(null);
        }

        foreach ($group->getPrices() as $price) {
            $entityManager->remove($price);
        }

        foreach ($group->getCodes() as $code) {
            $entityManager->remove($code);
        }

        $entityManager->remove($group);
        $entityManager->flush();
    }
}
