<?php

namespace App\Package\Repository;

use App\Package\Entity\Package;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

/** @extends ServiceEntityRepository<Package> */
class PackageRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Package::class);
    }

    public function findByUuid(string $uuid): ?Package
    {
        return $this->findOneBy(['uuid' => $uuid]);
    }

    /** @return Package[] */
    public function findForPair(string $entityType, int $entityId, ?bool $active = null): array
    {
        $qb = $this->createQueryBuilder('p')
            ->addSelect('s', 'i')
            ->leftJoin('p.services', 's')
            ->leftJoin('s.serviceItem', 'i')
            ->where('p.entityType = :type')
            ->andWhere('p.entityId = :id')
            ->setParameter('type', $entityType)
            ->setParameter('id', $entityId)
            ->orderBy('p.createdAt', 'DESC');

        if ($active !== null) {
            $qb->andWhere('p.active = :active')->setParameter('active', $active);
        }

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

    public function save(Package $package, bool $flush = true): void
    {
        $this->getEntityManager()->persist($package);

        if ($flush) {
            $this->getEntityManager()->flush();
        }
    }
}
