<?php

declare(strict_types=1);

/*
 * This file is part of the VITICORE2 package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Marketing\Repository;

use CpCreation\VitiCore\Marketing\Model\ProductReviewReport;
use CpCreation\VitiCore\Repository\BaseRepository;
use Doctrine\ORM\QueryBuilder;
use Doctrine\Persistence\ManagerRegistry;

final class ProductReviewReportRepository extends BaseRepository
{
    /** @throws \ReflectionException */
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, ProductReviewReport::class);
    }

    /** @return list<ProductReviewReport> */
    public function findLatestForAdmin(int $limit = 100): array
    {
        return $this->createAdminQueryBuilder()
            ->setMaxResults($limit)
            ->getQuery()
            ->getResult();
    }

    public function createAdminQueryBuilder(): QueryBuilder
    {
        return $this->createQueryBuilder('report')
            ->addSelect('review', 'product')
            ->addSelect('CASE WHEN report.status = :openStatus THEN 0 ELSE 1 END AS HIDDEN statusPriority')
            ->innerJoin('report.review', 'review')
            ->innerJoin('review.product', 'product')
            ->setParameter('openStatus', ProductReviewReport::STATUS_OPEN)
            ->orderBy('statusPriority', 'ASC')
            ->addOrderBy('report.reportedAt', 'DESC');
    }

    public function countOpen(): int
    {
        return $this->count(['status' => ProductReviewReport::STATUS_OPEN]);
    }
}
