<?php

namespace App\Patient\Repository;

use App\Patient\Entity\PatientRecord;
use App\Patient\Entity\PatientSession;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

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

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

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

    public function countByRecord(PatientRecord $record): int
    {
        return (int) $this->createQueryBuilder('s')
            ->select('COUNT(s.id)')
            ->where('s.record = :record')
            ->setParameter('record', $record)
            ->getQuery()
            ->getSingleScalarResult();
    }

    public function sumRevenue(string $entityType, int $entityId, int $from, int $to): int
    {
        $result = $this->createQueryBuilder('s')
            ->select('SUM(s.finalPriceRials)')
            ->join('s.record', 'r')
            ->where('r.entityType = :type')
            ->andWhere('r.entityId = :id')
            ->andWhere('s.createdAt BETWEEN :from AND :to')
            ->setParameter('type', $entityType)
            ->setParameter('id', $entityId)
            ->setParameter('from', $from)
            ->setParameter('to', $to)
            ->getQuery()
            ->getSingleScalarResult();

        return (int) ($result ?? 0);
    }

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