<?php

namespace App\Branch\Repository;

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

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

    /** @return BranchWorkingHours[] مرتب بر روز و سپس بازه */
    public function findForAddress(DoctorAddress $address): array
    {
        return $this->createQueryBuilder('h')
            ->where('h.address = :address')
            ->setParameter('address', $address)
            ->orderBy('h.dayOfWeek', 'ASC')
            ->addOrderBy('h.sequence', 'ASC')
            ->getQuery()
            ->getResult();
    }

    public function deleteForAddress(DoctorAddress $address): int
    {
        return (int) $this->createQueryBuilder('h')
            ->delete()
            ->where('h.address = :address')
            ->setParameter('address', $address)
            ->getQuery()
            ->execute();
    }

    /**
     * آدرس‌هایی که ساعت کاری تعریف‌شده دارند — برای نشان دادن وضعیت در لیست شعبه‌ها
     * بدون N+۱ کوئری.
     *
     * @param int[] $addressIds
     * @return array<int, int> شناسهٔ آدرس => تعداد بازه‌ها
     */
    public function countByAddressIds(array $addressIds): array
    {
        if ($addressIds === []) {
            return [];
        }

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

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

        return $counts;
    }
}
