<?php

namespace App\Inventory\Repository;

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

class InventoryPackageRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, InventoryPackage::class);
    }

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

    /** @return InventoryPackage[] */
    public function findByEntity(string $entityType, int $entityId): array
    {
        return $this->createQueryBuilder('p')
            ->leftJoin('p.items', 'pi')->addSelect('pi')
            ->leftJoin('pi.item', 'it')->addSelect('it')
            ->where('p.entityType = :type AND p.entityId = :id')
            ->setParameter('type', $entityType)
            ->setParameter('id', $entityId)
            ->orderBy('p.createdAt', 'DESC')
            ->getQuery()
            ->getResult();
    }

    /**
     * پکیج‌ها را با یک کوئری برمی‌گرداند (کلید = id) تا سریالایز کردن فهرست سرویس‌ها
     * به find()-per-row نیفتد.
     *
     * @param int[] $ids
     * @return array<int, InventoryPackage>
     */
    public function findMapByIds(array $ids): array
    {
        $ids = array_values(array_unique(array_filter($ids)));
        if ($ids === []) {
            return [];
        }

        $map = [];
        foreach ($this->findBy(['id' => $ids]) as $package) {
            $map[$package->getId()] = $package;
        }

        return $map;
    }

    public function save(InventoryPackage $package): void
    {
        $this->getEntityManager()->persist($package);
        $this->getEntityManager()->flush();
    }

    public function remove(InventoryPackage $package): void
    {
        $this->getEntityManager()->remove($package);
        $this->getEntityManager()->flush();
    }
}
