<?php declare(strict_types=1);
/**
 * This file is part of the SplendidBear Websites' projects.
 *
 * Copyright (c) 2026 @ www.splendidbear.org
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace App\Repository;

use App\Entity\RecentBattle;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\DBAL\Exception;
use Doctrine\Persistence\ManagerRegistry;
use RuntimeException;

/**
 * Class RecentBattleRepository
 *
 * @package  App\Repository
 * @author   Lang <https://www.splendidbear.org>
 * @category Class
 * @license  https://www.gnu.org/licenses/lgpl-3.0.en.html GNU Lesser General Public License
 * @link     www.splendidbear.org
 * @since    2026. 04. 20.
 *
 * @method RecentBattle|null find($id, $lockMode = null, $lockVersion = null)
 * @method RecentBattle|null findOneBy(array $criteria, array $orderBy = null)
 * @method RecentBattle[]    findAll()
 * @method RecentBattle[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class RecentBattleRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, RecentBattle::class);
    }

    public function findRecentForUser(int $userId, int $limit = 30): array
    {
        $qb = $this->createQueryBuilder('rb');

        return $qb
            ->where($qb->expr()->eq('rb.userId', ':uid'))
            ->andWhere(
                $qb->expr()->orX(
                    $qb->expr()->eq('rb.oppIsGuest', ':false'),
                    $qb->expr()->isNotNull('rb.redPoints'),
                    $qb->expr()->isNotNull('rb.bluePoints')
                ),
            )
            ->setParameter('uid', $userId)
            ->setParameter('false', false)
            ->orderBy('rb.updated', 'DESC')
            ->setMaxResults($limit)
            ->getQuery()
            ->getResult();
    }

    public function refreshMaterializedView(): void
    {
        try {
            $this
                ->getEntityManager()
                ->getConnection()
                ->executeStatement('REFRESH MATERIALIZED VIEW CONCURRENTLY recent_battles');
        } catch (Exception $e) {
            throw new RuntimeException("Failed to refresh materialized view: {$e->getMessage()}", 0, $e);
        }
    }
}
