<?php

namespace App\ClinicService\Repository;

use App\ClinicService\Entity\ServiceBranchOverride;
use App\ClinicService\Entity\ServiceItem;
use App\Doctor\Entity\DoctorAddress;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

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

    /** @return ServiceBranchOverride[] */
    public function findForItem(ServiceItem $item): array
    {
        return $this->createQueryBuilder('o')
            ->where('o.item = :item')
            ->setParameter('item', $item)
            ->getQuery()
            ->getResult();
    }

    /**
     * override های یک شعبه برای مجموعه‌ای از آیتم‌ها — یک کوئری، نه یکی per آیتم.
     *
     * @param int[] $itemIds
     * @return array<int, ServiceBranchOverride> کلید = شناسهٔ آیتم
     */
    public function mapForAddress(array $itemIds, DoctorAddress $address): array
    {
        if ($itemIds === []) {
            return [];
        }

        $rows = $this->createQueryBuilder('o')
            ->where('o.item IN (:ids)')
            ->andWhere('o.address = :address')
            ->setParameter('ids', $itemIds)
            ->setParameter('address', $address)
            ->getQuery()
            ->getResult();

        $map = [];
        foreach ($rows as $override) {
            $map[(int) $override->getItem()->getId()] = $override;
        }

        return $map;
    }

    public function deleteForItem(ServiceItem $item): int
    {
        return (int) $this->createQueryBuilder('o')
            ->delete()
            ->where('o.item = :item')
            ->setParameter('item', $item)
            ->getQuery()
            ->execute();
    }
}
