<?php

namespace App\Policy\Repository;

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

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

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

    /**
     * قانون‌های فعالِ یک دسته — یک کوئری per دسته، نه per قانون.
     *
     * @return Policy[]
     */
    public function findForCategory(string $entityType, int $entityId, string $category): array
    {
        return $this->createQueryBuilder('p')
            ->addSelect('a', 's', 'c')
            ->leftJoin('p.address', 'a')
            ->leftJoin('p.serviceItem', 's')
            ->leftJoin('p.catalogCategory', 'c')
            ->where('p.entityType = :type')
            ->andWhere('p.entityId = :id')
            ->andWhere('p.category = :category')
            ->andWhere('p.active = true')
            ->setParameter('type', $entityType)
            ->setParameter('id', $entityId)
            ->setParameter('category', $category)
            ->getQuery()
            ->getResult();
    }

    /** @return Policy[] */
    public function findForPair(string $entityType, int $entityId, ?string $category = null): array
    {
        $qb = $this->createQueryBuilder('p')
            ->where('p.entityType = :type')
            ->andWhere('p.entityId = :id')
            ->setParameter('type', $entityType)
            ->setParameter('id', $entityId)
            ->orderBy('p.priority', 'DESC')
            ->addOrderBy('p.createdAt', 'ASC');

        if ($category !== null) {
            $qb->andWhere('p.category = :category')->setParameter('category', $category);
        }

        return $qb->getQuery()->getResult();
    }
}
