<?php

namespace App\Rating\Repository;

use App\Auth\Entity\User;
use App\Doctor\Entity\Doctor;
use App\Rating\Entity\Rate;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

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

    public function findByUserAndDoctor(User $user, Doctor $doctor): ?Rate { return $this->findOneBy(['user' => $user, 'doctor' => $doctor]); }

    /**
     * Aggregate the five rating dimensions for a doctor.
     *
     * @return array{point: float, satisfaction: int, averages: list<array{name:string,label:string,progress:int}>}
     */
    public function getAggregate(Doctor $doctor): array
    {
        $row = $this->createQueryBuilder('r')
            ->select(
                'AVG(r.waitingTimeAtClinic) as waiting_time_at_clinic',
                'AVG(r.accuracyOfDiagnosis) as accuracy_of_diagnosis',
                'AVG(r.doctorBehavior) as doctor_behavior',
                'AVG(r.clinicCleanliness) as clinic_cleanliness',
                'AVG(r.doctorExpertise) as doctor_expertise'
            )
            ->where('r.doctor = :doctor')
            ->setParameter('doctor', $doctor)
            ->getQuery()->getSingleResult();

        $averages = [];
        $sum = 0;
        foreach (Rate::DIMENSIONS as $name => $label) {
            $progress = (int) round((float) ($row[$name] ?? 0));
            $averages[] = ['name' => $name, 'label' => $label, 'progress' => $progress];
            $sum += $progress;
        }

        $satisfaction = (int) round($sum / count(Rate::DIMENSIONS));

        return [
            'point'        => round($satisfaction / 20, 1),
            'satisfaction' => $satisfaction,
            'averages'     => $averages,
        ];
    }

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