<?php

namespace App\Tests\Secretary;

use App\Doctor\Entity\Doctor;
use App\Secretary\Entity\DoctorSecretary;
use App\Tests\ApiTestCase;

/**
 * The per-doctor secretary list must fetch-join secretary/doctor/clinic, not
 * lazy-load them per row. Query count stays constant with secretary count.
 */
class SecretaryListNPlusOneTest extends ApiTestCase
{
    /** @return array{0: \App\Auth\Entity\User, 1: Doctor} */
    private function makeDoctorWithSecretaries(int $count): array
    {
        $owner  = $this->createUser(['ROLE_DOCTOR']);
        $doctor = new Doctor($owner, 'دکتر');
        $this->em->persist($doctor);
        $this->em->flush();

        for ($i = 0; $i < $count; $i++) {
            $secUser = $this->createUser(['ROLE_SECRETARY']);
            $this->em->persist(new DoctorSecretary($doctor, $secUser, DoctorSecretary::OWNER_DOCTOR));
        }
        $this->em->flush();

        return [$owner, $doctor];
    }

    public function testQueryCountDoesNotGrowWithSecretaryCount(): void
    {
        $this->client->disableReboot();

        [$ownerS, $small] = $this->makeDoctorWithSecretaries(1);
        [$ownerL, $large] = $this->makeDoctorWithSecretaries(5);
        $this->em->clear();

        $qSmall = $this->countQueries(fn () => $this->authJson('GET', '/api/v1/secretaries/' . $small->getUuid(), $ownerS));
        $qLarge = $this->countQueries(fn () => $this->authJson('GET', '/api/v1/secretaries/' . $large->getUuid(), $ownerL));

        $this->assertLessThanOrEqual($qSmall + 1, $qLarge, "N+1: query count grew from $qSmall to $qLarge");
    }
}
