<?php

namespace App\Resource\Repository;

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

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

    public function findByUuid(string $uuid): ?TenantHolidayOverride
    {
        return $this->findOneBy(['uuid' => $uuid]);
    }

    public function findForDate(string $entityType, int $entityId, int $date): ?TenantHolidayOverride
    {
        return $this->findOneBy(['entityType' => $entityType, 'entityId' => $entityId, 'date' => $date]);
    }

    /**
     * @return array<int, TenantHolidayOverride> کلید = نیمه‌شب همان روز
     */
    public function mapForRange(string $entityType, int $entityId, int $from, int $to): array
    {
        $rows = $this->createQueryBuilder('o')
            ->where('o.entityType = :type')
            ->andWhere('o.entityId = :id')
            ->andWhere('o.date >= :from')
            ->andWhere('o.date <= :to')
            ->setParameter('type', $entityType)
            ->setParameter('id', $entityId)
            ->setParameter('from', $from)
            ->setParameter('to', $to)
            ->getQuery()
            ->getResult();

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

        return $map;
    }
}
