<?php

namespace App\Sms\Repository;

use App\Sms\Entity\SmsWallet;
use App\Sms\Entity\SmsWalletTransaction;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

class SmsWalletTransactionRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, SmsWalletTransaction::class);
    }

    public function findByWallet(SmsWallet $wallet, int $page = 1, int $limit = 20): array
    {
        return $this->createQueryBuilder('t')
            ->where('t.wallet = :wallet')
            ->setParameter('wallet', $wallet)
            ->orderBy('t.id', 'DESC')
            ->setFirstResult(($page - 1) * $limit)
            ->setMaxResults($limit)
            ->getQuery()
            ->getResult();
    }

    public function countByWallet(SmsWallet $wallet): int
    {
        return (int) $this->createQueryBuilder('t')
            ->select('COUNT(t.id)')
            ->where('t.wallet = :wallet')
            ->setParameter('wallet', $wallet)
            ->getQuery()
            ->getSingleScalarResult();
    }

    public function save(SmsWalletTransaction $tx): void
    {
        $this->getEntityManager()->persist($tx);
        $this->getEntityManager()->flush();
    }
}
