<?php

declare(strict_types=1);

namespace App\Repository;

use App\Entity\DrinkType;
use App\Entity\InventoryRecord;
use DateTimeImmutable;
use Doctrine\ORM\EntityManagerInterface;

/**
 * @extends AbstractRepository<InventoryRecord>
 */
class InventoryRecordRepository extends AbstractRepository
{
    public function __construct(EntityManagerInterface $entityManager)
    {
        parent::__construct($entityManager, $entityManager->getClassMetadata(InventoryRecord::class));
    }

    /**
     * @return array<int, InventoryRecord>
     */
    public function findByDrinkType(DrinkType $drinkType): array
    {
        return $this->findBy(
            [
                'drinkType' => $drinkType,
            ],
            [
                'timestamp' => 'DESC',
            ],
        );
    }

    public function findLatestByDrinkType(DrinkType $drinkType): null|InventoryRecord
    {
        $records = $this->findBy(
            [
                'drinkType' => $drinkType,
            ],
            [
                'timestamp' => 'DESC',
            ],
            1,
        );

        return $records[0] ?? null;
    }

    /**
     * @return array<int, InventoryRecord>
     */
    public function findByTimestampRange(DateTimeImmutable $start, DateTimeImmutable $end): array
    {
        $qb = $this->getEntityManager()->createQueryBuilder();
        $qb
            ->select('ir')
            ->from(InventoryRecord::class, 'ir')
            ->where('ir.timestamp >= :start')
            ->andWhere('ir.timestamp <= :end')
            ->setParameter('start', $start)
            ->setParameter('end', $end)
            ->orderBy('ir.timestamp', 'DESC');

        /** @var array<int, InventoryRecord> $result */
        $result = $qb->getQuery()->getResult();
        return $result;
    }
}
