<?php

namespace App\Patient\Repository;

use App\Appointment\Entity\Appointment;
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]);
    }

    /**
     * مراجعهٔ ساخته‌شده برای این نوبت در همین محیط، یا null.
     *
     * گاردِ ساختِ خودکار: قطعی‌شدنِ دوباره (confirmed → cancelled → confirmed) نباید
     * مراجعهٔ تکراری بسازد. مراجعهٔ آرشیوشده هم «ساخته‌شده» حساب می‌شود، وگرنه آرشیو
     * کردنِ یک مراجعهٔ اشتباه باعث ساخت دوباره‌اش می‌شود.
     */
    public function findByAppointmentAndEntity(Appointment $appointment, string $entityType, int $entityId): ?PatientSession
    {
        return $this->createQueryBuilder('s')
            ->join('s.record', 'r')
            ->where('s.appointment = :appointment')
            ->andWhere('r.entityType = :entityType')
            ->andWhere('r.entityId = :entityId')
            ->setParameter('appointment', $appointment)
            ->setParameter('entityType', $entityType)
            ->setParameter('entityId', $entityId)
            ->setMaxResults(1)
            ->getQuery()
            ->getOneOrNullResult();
    }

    /** $filter: all | active | archived. پیش‌فرض all برای حفظ رفتار callerهای موجود. */
    public function findByRecord(PatientRecord $record, int $page = 1, int $limit = 20, string $filter = 'all'): array
    {
        $qb = $this->createQueryBuilder('s')
            ->where('s.record = :record')
            ->setParameter('record', $record)
            ->orderBy('s.id', 'DESC')
            ->setFirstResult(($page - 1) * $limit)
            ->setMaxResults($limit);
        $this->applyArchivedFilter($qb, $filter);
        return $qb->getQuery()->getResult();
    }

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

    private function applyArchivedFilter(\Doctrine\ORM\QueryBuilder $qb, string $filter): void
    {
        if ($filter === 'active') {
            $qb->andWhere('s.archived = false');
        } elseif ($filter === 'archived') {
            $qb->andWhere('s.archived = true');
        }
    }

    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();
    }

    /**
     * تاریخ ثبت چند مراجعه — کلیددار بر اساس id جلسه.
     * @param int[] $ids
     * @return array<int, int> sessionId => createdAt
     */
    public function datesForIds(array $ids): array
    {
        if ($ids === []) {
            return [];
        }

        $rows = $this->createQueryBuilder('s')
            ->select('s.id AS id', 's.createdAt AS created_at')
            ->where('s.id IN (:ids)')
            ->setParameter('ids', $ids)
            ->getQuery()
            ->getArrayResult();

        $out = [];
        foreach ($rows as $r) {
            $out[(int) $r['id']] = (int) $r['created_at'];
        }
        return $out;
    }

    /**
     * نام و موبایل بیمار هر مراجعه — کلیددار بر اساس id جلسه.
     * @param int[] $ids
     * @return array<int, array{name: ?string, mobile: ?string}>
     */
    public function patientInfoForIds(array $ids): array
    {
        if ($ids === []) {
            return [];
        }

        $rows = $this->createQueryBuilder('s')
            ->select('s.id AS id', 'u.realName AS name', 'u.mobileNumber AS mobile')
            ->join('s.record', 'r')
            ->join('r.user', 'u')
            ->where('s.id IN (:ids)')
            ->setParameter('ids', $ids)
            ->getQuery()
            ->getArrayResult();

        $out = [];
        foreach ($rows as $r) {
            $out[(int) $r['id']] = ['name' => $r['name'], 'mobile' => $r['mobile']];
        }
        return $out;
    }
}
