<?php

declare(strict_types=1);

namespace Gls\GlsPoland\Repository;

use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Gls\GlsPoland\Entity\Consignment;

/**
 * @extends ServiceEntityRepository<Consignment>
 *
 * @method Consignment|null find($id, $lockMode = null, $lockVersion = null)
 * @method Consignment|null findOneBy(array $criteria, array $orderBy = null)
 * @method Consignment[] findAll()
 * @method Consignment[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class ConsignmentRepository extends EntityRepository
{
    public function add(Consignment $entity, bool $flush = true): void
    {
        $entityManager = $this->getEntityManager();
        $entityManager->persist($entity);
        if ($flush) {
            $entityManager->flush();
        }
    }

    public function remove(Consignment $entity, bool $flush = true): void
    {
        $entityManager = $this->getEntityManager();
        $entityManager->remove($entity);
        if ($flush) {
            $entityManager->flush();
        }
    }

    /**
     * @return Consignment[]
     */
    public function findWithoutPickups(int ...$consignmentIds): array
    {
        $qb = $this
            ->createQueryBuilder('c')
            ->addSelect('p')
            ->innerJoin('c.parcels', 'p')
            ->andWhere('c.pickupId IS NULL')
            ->orderBy('c.id', 'ASC');

        if ([] !== $consignmentIds) {
            $qb
                ->andWhere('c.id IN (:consignmentIds)')
                ->setParameter('consignmentIds', $consignmentIds);
        }

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

    protected static function getEntityClass(): string
    {
        return Consignment::class;
    }
}
