<?php

namespace App\Tests\Patient;

use App\Doctor\Entity\Doctor;
use App\Patient\Entity\PatientRecord;
use App\Patient\Repository\PatientRecordRepository;
use App\Tag\Entity\TenantTag;
use App\Tests\ApiTestCase;

/**
 * PatientRecord carries clinic-scoped case-file fields (record_number, gender,
 * birth_date, referral_source, description) and a set of TenantTag labels.
 */
class PatientRecordFieldsTest extends ApiTestCase
{
    public function testFieldsAndTagsRoundTrip(): void
    {
        $owner  = $this->createUser(['ROLE_DOCTOR']);
        $doctor = new Doctor($owner, 'دکتر');
        $this->em->persist($doctor);
        $this->em->flush();

        $t1 = new TenantTag('doctor', $doctor->getId(), 'فوری', '#FF0000');
        $t2 = new TenantTag('doctor', $doctor->getId(), 'پیگیری', '#00AA00');
        $this->em->persist($t1);
        $this->em->persist($t2);
        $this->em->flush();

        $patient = $this->createUser(['ROLE_USER']);   // random unique mobile — db_test is never reset
        $patient->setRealName('بیمار نمونه');
        $this->em->flush();

        $record = new PatientRecord('doctor', $doctor->getId(), $patient, 'doctor', $doctor->getId());
        $record->setRecordNumber('P-1001')
            ->setTags([$t1, $t2]);
        $this->em->persist($record);
        $this->em->flush();
        $uuid = $record->getUuid();
        $this->em->clear();

        /** @var PatientRecordRepository $repo */
        $repo     = static::getContainer()->get(PatientRecordRepository::class);
        $reloaded = $repo->findByUuid($uuid);
        self::assertNotNull($reloaded);
        self::assertCount(2, $reloaded->getTags());

        $arr = $reloaded->toArray();
        self::assertSame('P-1001', $arr['record_number']);
        self::assertCount(2, $arr['tags']);
        self::assertSame('فوری', $arr['tags'][0]['name']);
    }
}
