<?php

namespace App\Tests\Doctor;

use App\Doctor\Entity\Doctor;
use App\Shared\Util\PersianText;
use App\Tests\ApiTestCase;

/**
 * A doctor's stored name never carries the «دکتر» title — the display layer
 * decides how to present it. DoctorImportService and DoctorClaimService already
 * enforced this; the ordinary registration paths did not, so a name typed as
 * «دکتر حامد حسینی» was stored verbatim and then rendered «دکتر دکتر حامد حسینی».
 */
class DoctorNameTitleTest extends ApiTestCase
{
    /** db_test is never reset, so a fixed mobile collides across runs. */
    private function freshMobile(): string
    {
        return '09' . str_pad((string) random_int(0, 999_999_999), 9, '0', STR_PAD_LEFT);
    }

    private function createDoctorAs(string $name): ?Doctor
    {
        $admin  = $this->createUser(['ROLE_ADMIN']);
        $mobile = $this->freshMobile();

        $this->authJson('POST', '/api/v1/admin/doctors', $admin, [
            'mobile' => $mobile,
            'name'   => $name,
        ]);

        $this->assertSame(201, $this->responseCode());

        return $this->em->getRepository(Doctor::class)
            ->createQueryBuilder('d')
            ->join('d.user', 'u')->where('u.mobileNumber = :m')->setParameter('m', $mobile)
            ->getQuery()->getOneOrNullResult();
    }

    public function testAdminCreateStripsTheTitle(): void
    {
        $doctor = $this->createDoctorAs('دکتر حامد حسینی');

        $this->assertNotNull($doctor);
        $this->assertSame('حامد حسینی', $doctor->getName());
    }

    public function testPlainNameIsLeftAlone(): void
    {
        $doctor = $this->createDoctorAs('حامد حسینی');

        $this->assertNotNull($doctor);
        $this->assertSame('حامد حسینی', $doctor->getName());
    }

    #[\PHPUnit\Framework\Attributes\DataProvider('titleVariants')]
    public function testStripDoctorTitle(string $input, string $expected): void
    {
        $this->assertSame($expected, PersianText::stripDoctorTitle($input));
    }

    public static function titleVariants(): array
    {
        return [
            'plain'            => ['حامد حسینی', 'حامد حسینی'],
            'single title'     => ['دکتر حامد حسینی', 'حامد حسینی'],
            'repeated title'   => ['دکتر دکتر حامد حسینی', 'حامد حسینی'],
            'extra whitespace' => ['  دکتر   حامد حسینی  ', 'حامد حسینی'],
            'title inside'     => ['حامد دکتر حسینی', 'حامد دکتر حسینی'],
        ];
    }
}
