<?php

namespace App\Policy\Repository;

use App\Policy\Entity\Policy;
use App\Policy\Entity\PolicySimulationRun;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

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

    /** آخرین اجرای آزمایشی این قانون، از هر نسخه‌ای. */
    public function latestFor(Policy $policy): ?PolicySimulationRun
    {
        return $this->createQueryBuilder('r')
            ->where('r.policy = :policy')
            ->setParameter('policy', $policy)
            ->orderBy('r.createdAt', 'DESC')
            ->addOrderBy('r.id', 'DESC')
            ->setMaxResults(1)
            ->getQuery()
            ->getOneOrNullResult();
    }

    /** @return PolicySimulationRun[] */
    public function historyFor(Policy $policy, int $limit = 10): array
    {
        return $this->createQueryBuilder('r')
            ->where('r.policy = :policy')
            ->setParameter('policy', $policy)
            ->orderBy('r.createdAt', 'DESC')
            ->addOrderBy('r.id', 'DESC')
            ->setMaxResults($limit)
            ->getQuery()
            ->getResult();
    }

    public function save(PolicySimulationRun $run): void
    {
        $em = $this->getEntityManager();
        $em->persist($run);
        $em->flush();
    }
}
