<?php

namespace App\Resource\Repository;

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

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

    public function countForSkill(Skill $skill): int
    {
        return (int) $this->createQueryBuilder('rs')
            ->select('COUNT(rs.id)')
            ->where('rs.skill = :skill')
            ->setParameter('skill', $skill)
            ->getQuery()
            ->getSingleScalarResult();
    }

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

        $rows = $this->createQueryBuilder('rs')
            ->select('IDENTITY(rs.skill) AS skill_id, COUNT(rs.id) AS total')
            ->where('rs.skill IN (:ids)')
            ->setParameter('ids', $skillIds)
            ->groupBy('rs.skill')
            ->getQuery()
            ->getArrayResult();

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

        return $counts;
    }

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