<?php

namespace App\Settlement\Repository;

use App\Auth\Entity\User;
use App\Settlement\Entity\Settlement;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

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

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

    /** @return Settlement[] */
    public function findByUser(User $user, int $limit = 50, int $offset = 0): array
    {
        return $this->findBy(['user' => $user], ['createdAt' => 'DESC'], $limit, $offset);
    }

    public function countByUser(User $user): int
    {
        return $this->count(['user' => $user]);
    }

    /** Balance = sum of credits - sum of debits from wallet_transactions */
    public function getWalletBalance(User $user): int
    {
        $em = $this->getEntityManager();

        $credit = (int) ($em->createQuery(
            'SELECT SUM(w.amountRials) FROM App\Settlement\Entity\WalletTransaction w
             WHERE w.user = :user AND w.type = :type'
        )->setParameters(['user' => $user, 'type' => 'credit'])->getSingleScalarResult() ?? 0);

        $debit = (int) ($em->createQuery(
            'SELECT SUM(w.amountRials) FROM App\Settlement\Entity\WalletTransaction w
             WHERE w.user = :user AND w.type = :type'
        )->setParameters(['user' => $user, 'type' => 'debit'])->getSingleScalarResult() ?? 0);

        return $credit - $debit;
    }

    /** @param string[] $statuses */
    public function sumByStatus(User $user, array $statuses): int
    {
        return (int) ($this->getEntityManager()->createQuery(
            'SELECT SUM(s.amountRials) FROM App\Settlement\Entity\Settlement s
             WHERE s.user = :user AND s.status IN (:statuses)'
        )->setParameters(['user' => $user, 'statuses' => $statuses])
         ->getSingleScalarResult() ?? 0);
    }

    public function save(Settlement $entity, bool $flush = true): void
    {
        $this->getEntityManager()->persist($entity);
        if ($flush) $this->getEntityManager()->flush();
    }
}
