<?php

namespace App\Doctor\Command;

use App\Auth\Entity\User;
use App\Doctor\Entity\Doctor;
use App\Doctor\Service\DoctorImportService;
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;

/**
 * backfill یک‌بارمصرف: نقش ROLE_UNCLAIMED_DOCTOR برای کاربران جانشینِ ایمپورت
 * (mobile با پیشوند imp_، غیرفعال، متصل به پزشک unclaimed) که پیش از افزودن
 * این نقش ساخته شده‌اند. غیرمخرب؛ با --dry-run فقط گزارش می‌دهد.
 *
 *   php bin/console app:doctors:backfill-surrogate-role --dry-run
 *   php bin/console app:doctors:backfill-surrogate-role
 */
#[AsCommand(
    name: 'app:doctors:backfill-surrogate-role',
    description: 'Add ROLE_UNCLAIMED_DOCTOR to legacy IRIMC surrogate users (idempotent, supports --dry-run)',
)]
class BackfillSurrogateRoleCommand 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 User[] $surrogates */
        $surrogates = $this->em->createQueryBuilder()
            ->select('u')
            ->from(User::class, 'u')
            ->join(Doctor::class, 'd', 'WITH', 'd.user = u')
            ->where("u.mobileNumber LIKE 'imp\\_%'")
            ->andWhere('u.status = 0')
            ->andWhere("d.ownerStatus = 'unclaimed'")
            ->getQuery()
            ->getResult();

        $updated = 0;
        foreach ($surrogates as $user) {
            if ($user->hasRole(DoctorImportService::ROLE_UNCLAIMED_DOCTOR)) {
                continue;
            }
            $updated++;
            $io->text(sprintf('%s %s', $dryRun ? '[dry-run]' : '[update]', $user->getMobileNumber()));
            if (!$dryRun) {
                $user->addRole(DoctorImportService::ROLE_UNCLAIMED_DOCTOR);
            }
        }

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

        $io->success(sprintf('%d surrogate(s) %s (of %d scanned)', $updated, $dryRun ? 'would be updated' : 'updated', count($surrogates)));

        return Command::SUCCESS;
    }
}
