<?php

namespace App\Resource\Repository;

use App\Resource\Entity\ClinicResource;
use App\Resource\Entity\ResourceCalendar;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

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

    /** @return ResourceCalendar[] */
    public function findForResource(ClinicResource $resource): array
    {
        return $this->createQueryBuilder('c')
            ->where('c.resource = :resource')
            ->setParameter('resource', $resource)
            ->orderBy('c.dayOfWeek', 'ASC')
            ->addOrderBy('c.sequence', 'ASC')
            ->getQuery()
            ->getResult();
    }

    /**
     * شیفت‌های چند منبع با **یک** کوئری — گزارش بهره‌وری روی چهل منبع، چهل کوئری نمی‌خواهد.
     *
     * @param int[] $resourceIds
     * @return array<int, list<\App\Resource\Entity\ResourceCalendar>> کلید: شناسهٔ منبع
     */
    public function findForResources(array $resourceIds): array
    {
        if ($resourceIds === []) {
            return [];
        }

        $rows = $this->createQueryBuilder('c')
            ->where('IDENTITY(c.resource) IN (:ids)')
            ->setParameter('ids', $resourceIds)
            ->orderBy('c.dayOfWeek', 'ASC')
            ->addOrderBy('c.sequence', 'ASC')
            ->getQuery()
            ->getResult();

        $byResource = [];
        foreach ($rows as $row) {
            $byResource[(int) $row->getResource()->getId()][] = $row;
        }

        return $byResource;
    }

    public function deleteForResource(ClinicResource $resource): int
    {
        return (int) $this->createQueryBuilder('c')
            ->delete()
            ->where('c.resource = :resource')
            ->setParameter('resource', $resource)
            ->getQuery()
            ->execute();
    }

    /**
     * @param int[] $resourceIds
     * @return array<int, int> شناسهٔ منبع => تعداد شیفت
     */
    public function countByResourceIds(array $resourceIds): array
    {
        if ($resourceIds === []) {
            return [];
        }

        $rows = $this->createQueryBuilder('c')
            ->select('IDENTITY(c.resource) AS resource_id, COUNT(c.id) AS total')
            ->where('c.resource IN (:ids)')
            ->setParameter('ids', $resourceIds)
            ->groupBy('c.resource')
            ->getQuery()
            ->getArrayResult();

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

        return $counts;
    }
}
