<?php

namespace App\Branch\Repository;

use App\Branch\Entity\Room;
use App\Doctor\Entity\DoctorAddress;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

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

    /**
     * uuid از request می‌آید، ولی Room جفت محیط دارد پس TenantFilter اتاق محیط دیگر را
     * پیش از رسیدن به اینجا حذف می‌کند — همان دلیلی که در TenantLookupInventoryTest
     * برای این lookup ثبت شده.
     */
    public function findByUuid(string $uuid): ?Room
    {
        return $this->findOneBy(['uuid' => $uuid]);
    }

    /** @return Room[] */
    public function findForAddress(DoctorAddress $address): array
    {
        return $this->createQueryBuilder('r')
            ->where('r.address = :address')
            ->setParameter('address', $address)
            ->orderBy('r.name', 'ASC')
            ->getQuery()
            ->getResult();
    }

    public function countActiveForAddress(DoctorAddress $address): int
    {
        return (int) $this->createQueryBuilder('r')
            ->select('COUNT(r.id)')
            ->where('r.address = :address')
            ->andWhere('r.active = true')
            ->setParameter('address', $address)
            ->getQuery()
            ->getSingleScalarResult();
    }

    /**
     * @param int[] $addressIds
     * @return array<int, int> شناسهٔ آدرس => تعداد اتاق فعال
     */
    public function countActiveByAddressIds(array $addressIds): array
    {
        if ($addressIds === []) {
            return [];
        }

        $rows = $this->createQueryBuilder('r')
            ->select('IDENTITY(r.address) AS address_id, COUNT(r.id) AS total')
            ->where('r.address IN (:ids)')
            ->andWhere('r.active = true')
            ->setParameter('ids', $addressIds)
            ->groupBy('r.address')
            ->getQuery()
            ->getArrayResult();

        $counts = [];
        foreach ($rows as $row) {
            $counts[(int) $row['address_id']] = (int) $row['total'];
        }

        return $counts;
    }
}
