<?php

namespace App\ClinicService\Repository;

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

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

    public function findForServiceYear(int $serviceItemId, int $year): ?Tariff
    {
        return $this->findOneBy([
            'serviceItemId' => $serviceItemId,
            'year'          => $year,
            'isActive'      => true,
        ]);
    }

    /** @return Tariff[] */
    public function findByService(int $serviceItemId): array
    {
        return $this->createQueryBuilder('t')
            ->where('t.serviceItemId = :sid')
            ->setParameter('sid', $serviceItemId)
            ->orderBy('t.year', 'DESC')
            ->getQuery()
            ->getResult();
    }

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

    public function save(Tariff $entity, bool $flush = true): void
    {
        $this->getEntityManager()->persist($entity);
        if ($flush) {
            $this->getEntityManager()->flush();
        }
    }
}
