<?php

namespace App\Inventory\Repository;

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

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

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

    /** @return InventoryItem[] */
    public function findByEntity(string $entityType, int $entityId): array
    {
        return $this->createQueryBuilder('i')
            ->where('i.entityType = :type AND i.entityId = :id')
            ->setParameter('type', $entityType)
            ->setParameter('id', $entityId)
            ->orderBy('i.name', 'ASC')
            ->getQuery()
            ->getResult();
    }

    /**
     * Distinct non-empty category values actually in use by the tenant — powers the
     * category filter dropdown on the inventory page.
     *
     * @return string[]
     */
    public function findCategories(string $entityType, int $entityId): array
    {
        $rows = $this->createQueryBuilder('i')
            ->select('DISTINCT i.category AS category')
            ->where('i.entityType = :type AND i.entityId = :id AND i.category IS NOT NULL AND i.category != :empty')
            ->setParameter('type', $entityType)
            ->setParameter('id', $entityId)
            ->setParameter('empty', '')
            ->orderBy('i.category', 'ASC')
            ->getQuery()
            ->getArrayResult();

        return array_map(static fn(array $r): string => $r['category'], $rows);
    }

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

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