<?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\UserStats;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\DBAL\Exception;
use Doctrine\Persistence\ManagerRegistry;
use RuntimeException;

/**
 * Class UserStatsRepository
 *
 * @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 UserStats|null find($id, $lockMode = null, $lockVersion = null)
 * @method UserStats|null findOneBy(array $criteria, array $orderBy = null)
 * @method UserStats[] findAll()
 * @method UserStats[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class UserStatsRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, UserStats::class);
    }

    public function findByUserId(int $userId): ?UserStats
    {
        return $this->find($userId);
    }

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