<?php

namespace App\Tests\ClinicService;

use App\ClinicService\Entity\ServiceItem;
use App\ClinicService\Entity\ServiceSection;
use App\ClinicService\Entity\Tariff;
use App\Doctor\Entity\Doctor;
use App\Insurance\Entity\TenantServiceCoverage;
use App\Tests\ApiTestCase;

/**
 * Deleting a service item must also remove its config rows (tariffs and
 * tenant-coverage), which reference it by a raw int with no FK and would
 * otherwise orphan.
 */
class ServiceItemDeleteCleanupTest extends ApiTestCase
{
    public function testDeletingItemPurgesTariffAndCoverage(): void
    {
        $owner  = $this->createUser(['ROLE_DOCTOR']);
        $doctor = new Doctor($owner, 'دکتر');
        $this->em->persist($doctor);
        $this->em->flush();

        $section = new ServiceSection('doctor', $doctor->getId(), 'بخش');
        $item    = new ServiceItem($section, 'خدمت');
        $this->em->persist($section);
        $this->em->persist($item);
        $this->em->flush();
        $itemId = $item->getId();

        $this->em->persist(new Tariff($itemId, 1404, 1000));
        $this->em->persist(new TenantServiceCoverage(999_999, $itemId));
        $this->em->flush();

        $this->authJson('DELETE', '/api/v1/service-item/' . $item->getUuid(), $owner);
        $this->assertSame(200, $this->responseCode());

        $this->em->clear();
        $this->assertCount(0, $this->em->getRepository(Tariff::class)->findBy(['serviceItemId' => $itemId]));
        $this->assertCount(0, $this->em->getRepository(TenantServiceCoverage::class)->findBy(['serviceItemId' => $itemId]));
    }
}
