<?php

namespace App\Secretary\Repository;

use App\Auth\Entity\User;
use App\Clinic\Entity\Clinic;
use App\Doctor\Entity\Doctor;
use App\Secretary\Entity\DoctorSecretary;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

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

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

    public function countActiveByDoctor(Doctor $doctor): int
    {
        return (int) $this->createQueryBuilder('s')
            ->select('COUNT(s.id)')
            ->where('s.doctor = :doctor')
            ->andWhere('s.active = true')
            ->setParameter('doctor', $doctor)
            ->getQuery()
            ->getSingleScalarResult();
    }

    /** @return DoctorSecretary[] */
    public function findByDoctor(Doctor $doctor): array
    {
        return $this->findBy(['doctor' => $doctor], ['createdAt' => 'DESC']);
    }

    /** Base query with secretary/doctor/clinic fetch-joined for toArray() (no N+1). */
    private function listWithRelations(): \Doctrine\ORM\QueryBuilder
    {
        return $this->createQueryBuilder('s')
            ->addSelect('sec', 'doc', 'cl')
            ->leftJoin('s.secretary', 'sec')
            ->leftJoin('s.doctor', 'doc')
            ->leftJoin('s.clinic', 'cl')
            ->orderBy('s.createdAt', 'DESC');
    }

    /** منشی ها مطب شخصی یک دکتر (owner_type='doctor') */
    public function findByDoctorScope(Doctor $doctor): array
    {
        return $this->listWithRelations()
            ->where('s.doctor = :doctor')
            ->andWhere('s.ownerType = :type')
            ->setParameter('doctor', $doctor)
            ->setParameter('type', DoctorSecretary::OWNER_DOCTOR)
            ->getQuery()
            ->getResult();
    }

    /** رابطه منشی در scope مطب شخصی */
    public function findActiveBySecretaryForDoctor(User $user, Doctor $doctor): ?DoctorSecretary
    {
        return $this->findOneBy([
            'secretary' => $user,
            'doctor'    => $doctor,
            'ownerType' => DoctorSecretary::OWNER_DOCTOR,
            'active'    => true,
        ]);
    }

    /** اولین رابطه فعال منشی در یک کلینیک (برای چک دسترسی کلی) */
    public function findActiveBySecretaryForClinic(User $user, Clinic $clinic): ?DoctorSecretary
    {
        return $this->createQueryBuilder('s')
            ->where('s.secretary = :user')
            ->andWhere('s.clinic = :clinic')
            ->andWhere('s.ownerType = :type')
            ->andWhere('s.active = true')
            ->setParameter('user', $user)
            ->setParameter('clinic', $clinic)
            ->setParameter('type', DoctorSecretary::OWNER_CLINIC)
            ->setMaxResults(1)
            ->getQuery()
            ->getOneOrNullResult();
    }

    /** همه دکترهای کلینیک که این منشی به آن‌ها متصل است */
    public function findDoctorsBySecretaryInClinic(User $user, Clinic $clinic): array
    {
        return $this->createQueryBuilder('s')
            ->select('d')
            ->join('s.doctor', 'd')
            ->where('s.secretary = :user')
            ->andWhere('s.clinic = :clinic')
            ->andWhere('s.ownerType = :type')
            ->andWhere('s.active = true')
            ->setParameter('user', $user)
            ->setParameter('clinic', $clinic)
            ->setParameter('type', DoctorSecretary::OWNER_CLINIC)
            ->getQuery()
            ->getResult();
    }

    /** همه روابط فعال یک منشی — برای auth context builder */
    public function findAllActiveBySecretary(User $user): array
    {
        return $this->findBy(['secretary' => $user, 'active' => true]);
    }

    /** اولین رابطه فعال — backward compat برای کدهایی که هنوز migrate نشده‌اند */
    public function findActiveBySecretary(User $user): ?DoctorSecretary
    {
        return $this->findOneBy(['secretary' => $user, 'active' => true]);
    }

    public function isDoctorInClinic(Doctor $doctor, Clinic $clinic): bool
    {
        return $clinic->getDoctors()->contains($doctor);
    }

    /** همه منشی ها کلینیک (owner_type='clinic') */
    public function findByClinic(Clinic $clinic): array
    {
        return $this->listWithRelations()
            ->where('s.clinic = :clinic')
            ->andWhere('s.ownerType = :type')
            ->setParameter('clinic', $clinic)
            ->setParameter('type', DoctorSecretary::OWNER_CLINIC)
            ->getQuery()
            ->getResult();
    }

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

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