<?php

namespace App\Subscription\Repository;

use App\Subscription\Entity\ClinicSubscription;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

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

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

    public function findActive(string $entityType, int $entityId): ?ClinicSubscription
    {
        return $this->createQueryBuilder('s')
            ->where('s.entityType = :type')
            ->andWhere('s.entityId = :id')
            ->andWhere('s.expiresAt IS NULL OR s.expiresAt > :now')
            ->setParameter('type', $entityType)
            ->setParameter('id', $entityId)
            ->setParameter('now', time())
            ->orderBy('s.id', 'DESC')
            ->setMaxResults(1)
            ->getQuery()
            ->getOneOrNullResult();
    }

    public function hasUsedTrial(string $entityType, int $entityId): bool
    {
        $count = $this->createQueryBuilder('s')
            ->select('COUNT(s.id)')
            ->where('s.entityType = :type')
            ->andWhere('s.entityId = :id')
            ->andWhere('s.isTrial = true')
            ->setParameter('type', $entityType)
            ->setParameter('id', $entityId)
            ->getQuery()
            ->getSingleScalarResult();

        return $count > 0;
    }

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

    public function findByPayment(\App\Payment\Entity\Payment $payment): ?ClinicSubscription
    {
        return $this->findOneBy(['payment' => $payment]);
    }

    public function remove(ClinicSubscription $subscription): void
    {
        $this->getEntityManager()->remove($subscription);
        $this->getEntityManager()->flush();
    }
}
