<?php

namespace App\Tests\Billing;

use App\Billing\Entity\Claim;
use App\Billing\Entity\ClaimItem;
use App\Doctor\Entity\Doctor;
use App\Insurance\Entity\Insurance;
use App\Insurance\Enum\InsuranceType;
use App\Tests\ApiTestCase;

/**
 * GET /billing/claims must batch items + insurance names, not lazy-load per
 * claim. Query count stays constant with claim count.
 */
class ClaimsListNPlusOneTest extends ApiTestCase
{
    /** @return \App\Auth\Entity\User */
    private function makeTenantWithClaims(int $count)
    {
        $owner  = $this->createUser(['ROLE_DOCTOR']);
        $doctor = new Doctor($owner, 'دکتر');
        $this->em->persist($doctor);
        $insurance = new Insurance('بیمه', InsuranceType::Basic);
        $this->em->persist($insurance);
        $this->em->flush();

        for ($i = 0; $i < $count; $i++) {
            $claim = new Claim('doctor', $doctor->getId(), $insurance->getId(), 'base');
            $item  = new ClaimItem($claim, 1, 100_000);
            $claim->addItem($item);
            $claim->submit();
            $this->em->persist($claim);
            $this->em->persist($item);
        }
        $this->em->flush();

        return $owner;
    }

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

        $ownerS = $this->makeTenantWithClaims(1);
        $ownerL = $this->makeTenantWithClaims(5);
        $this->em->clear();

        $qSmall = $this->countQueries(fn () => $this->authJson('GET', '/api/v1/billing/claims', $ownerS));
        $qLarge = $this->countQueries(fn () => $this->authJson('GET', '/api/v1/billing/claims', $ownerL));

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