<?php

namespace App\Doctor\Repository;

use App\Doctor\Entity\Doctor;
use App\Doctor\Entity\DoctorAddress;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

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

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

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

    public function findByUuidAndClinic(string $uuid, int $clinicId): ?DoctorAddress
    {
        return $this->createQueryBuilder('a')
            ->where('a.uuid = :uuid')
            ->andWhere('a.clinicId = :clinicId')
            ->setParameter('uuid', $uuid)
            ->setParameter('clinicId', $clinicId)
            ->getQuery()
            ->getOneOrNullResult();
    }

    public function findOneByClinic(int $clinicId): ?DoctorAddress
    {
        return $this->createQueryBuilder('a')
            ->where('a.clinicId = :clinicId')
            ->setParameter('clinicId', $clinicId)
            ->orderBy('a.id', 'ASC')
            ->setMaxResults(1)
            ->getQuery()
            ->getOneOrNullResult();
    }

    public function countByClinic(int $clinicId): int
    {
        return (int) $this->createQueryBuilder('a')
            ->select('COUNT(a.id)')
            ->where('a.clinicId = :clinicId')
            ->setParameter('clinicId', $clinicId)
            ->getQuery()
            ->getSingleScalarResult();
    }

    public function findAvailableForDoctor(Doctor $doctor, array $clinicIds): array
    {
        $qb = $this->createQueryBuilder('a');
        $qb->where(
            $qb->expr()->orX(
                $qb->expr()->andX(
                    $qb->expr()->eq('a.doctor', ':doctor'),
                    $qb->expr()->eq('a.type', ':personal')
                ),
                $qb->expr()->andX(
                    $qb->expr()->in('a.clinicId', ':clinicIds'),
                    $qb->expr()->eq('a.type', ':clinic')
                )
            )
        )
        ->setParameter('doctor', $doctor)
        ->setParameter('personal', DoctorAddress::TYPE_PERSONAL)
        ->setParameter('clinicIds', empty($clinicIds) ? [0] : $clinicIds)
        ->setParameter('clinic', DoctorAddress::TYPE_CLINIC);

        return $qb->getQuery()->getResult();
    }
}
