<?php

namespace App\Doctor\Command;

use App\Doctor\Entity\Doctor;
use App\Shared\Util\PersianText;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

/**
 * اصلاح یک‌بارمصرف نامِ پزشکانِ ایمپورت‌شدهٔ IRIMC که با پیشوند «دکتر» ذخیره شده‌اند.
 * فقط source='irimc' را دست می‌زند؛ پزشکان manual/seed را تغییر نمی‌دهد.
 *
 *   php bin/console app:doctors:fix-irimc-names --dry-run
 *   php bin/console app:doctors:fix-irimc-names
 */
#[AsCommand(
    name: 'app:doctors:fix-irimc-names',
    description: 'Strip the leading «دکتر» title from existing IRIMC doctor names (idempotent, supports --dry-run)',
)]
class FixIrimcNamesCommand extends Command
{
    public function __construct(private readonly EntityManagerInterface $em)
    {
        parent::__construct();
    }

    protected function configure(): void
    {
        $this->addOption('dry-run', null, InputOption::VALUE_NONE, 'Report only, change nothing');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io     = new SymfonyStyle($input, $output);
        $dryRun = (bool) $input->getOption('dry-run');

        /** @var Doctor[] $doctors */
        $doctors = $this->em->getRepository(Doctor::class)->createQueryBuilder('d')
            ->where('d.source = :src')
            ->setParameter('src', 'irimc')
            ->getQuery()
            ->getResult();

        $fixed = 0;
        foreach ($doctors as $doctor) {
            $clean = PersianText::stripDoctorTitle((string) $doctor->getName());
            if ($clean !== '' && $clean !== $doctor->getName()) {
                $io->text(sprintf('%s «%s» → «%s»', $dryRun ? '[dry-run]' : '[fix]', $doctor->getName(), $clean));
                if (!$dryRun) {
                    $doctor->setName($clean);
                }
                $fixed++;
            }
        }

        if (!$dryRun && $fixed > 0) {
            $this->em->flush();
        }

        $io->success(sprintf('%d نام %s (از %d پزشک IRIMC).', $fixed, $dryRun ? 'قابل اصلاح' : 'اصلاح شد', count($doctors)));

        return Command::SUCCESS;
    }
}
