<?php

namespace App\Pricing\Repository;

use App\ClinicService\Entity\ServiceItem;
use App\Pricing\Entity\PriceList;
use App\Pricing\Entity\PriceListItem;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

/**
 * @extends ServiceEntityRepository<PriceListItem>
 */
class PriceListItemRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, PriceListItem::class);
    }

    public function deleteForList(PriceList $list): int
    {
        return (int) $this->createQueryBuilder('i')
            ->delete()
            ->where('i.priceList = :list')
            ->setParameter('list', $list)
            ->getQuery()
            ->execute();
    }

    /**
     * قیمت چند سرویس در یک لیست — یک کوئری، نه یکی per سرویس.
     *
     * @param ServiceItem[] $services
     * @return array<int, int> شناسهٔ سرویس => قیمت
     */
    public function priceMap(PriceList $list, array $services): array
    {
        if ($services === []) {
            return [];
        }

        $rows = $this->createQueryBuilder('i')
            ->select('IDENTITY(i.serviceItem) AS service_id, i.priceRials AS price')
            ->where('i.priceList = :list')
            ->andWhere('i.serviceItem IN (:services)')
            ->setParameter('list', $list)
            ->setParameter('services', $services)
            ->getQuery()
            ->getArrayResult();

        $map = [];
        foreach ($rows as $row) {
            $map[(int) $row['service_id']] = (int) $row['price'];
        }

        return $map;
    }
}
