<?php

namespace App\Billing\Repository;

use App\Billing\Entity\ClaimStatusLog;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

class ClaimStatusLogRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, ClaimStatusLog::class);
    }

    /**
     * تاریخچه‌ی چند مطالبه در یک رفت‌وآمد، گروه‌بندی‌شده بر اساس claim_id.
     *
     * @param int[] $claimIds
     * @return array<int, array<int, array<string, mixed>>>
     */
    public function timelinesForClaims(array $claimIds): array
    {
        if ($claimIds === []) {
            return [];
        }

        $logs = $this->createQueryBuilder('l')
            ->where('l.claimId IN (:ids)')
            ->setParameter('ids', $claimIds)
            ->orderBy('l.createdAt', 'ASC')
            ->addOrderBy('l.id', 'ASC')
            ->getQuery()
            ->getResult();

        $grouped = [];
        foreach ($logs as $log) {
            $grouped[$log->getClaimId()][] = $log->toArray();
        }

        return $grouped;
    }

    public function save(ClaimStatusLog $entity, bool $flush = true): void
    {
        $this->getEntityManager()->persist($entity);
        if ($flush) {
            $this->getEntityManager()->flush();
        }
    }
}
