<?php

namespace App\Command;

use App\Entity\Child;
use App\Entity\Family;
use App\Repository\FamilyRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

#[AsCommand(name: 'app:child:create', description: 'Ajoute un profil enfant à une famille.')]
final class CreateChildCommand extends Command
{
    public function __construct(
        private readonly FamilyRepository $families,
        private readonly EntityManagerInterface $entityManager,
    ) {
        parent::__construct();
    }

    protected function configure(): void
    {
        $this
            ->addArgument('family-id', InputArgument::REQUIRED, 'Identifiant de la famille')
            ->addArgument('first-name', InputArgument::REQUIRED, 'Prénom')
            ->addArgument('display-order', InputArgument::OPTIONAL, 'Ordre d’affichage', 0);
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $family = $this->families->find((int) $input->getArgument('family-id'));
        if (!$family instanceof Family) {
            $output->writeln('<error>Famille introuvable.</error>');

            return Command::INVALID;
        }

        $firstName = trim((string) $input->getArgument('first-name'));
        if ('' === $firstName || mb_strlen($firstName) > 80) {
            $output->writeln('<error>Le prénom doit contenir entre 1 et 80 caractères.</error>');

            return Command::INVALID;
        }

        $child = new Child($family, $firstName, (int) $input->getArgument('display-order'));
        $this->entityManager->persist($child);
        $this->entityManager->flush();
        $output->writeln(sprintf('<info>Enfant créé avec l’identifiant %d.</info>', $child->getId()));

        return Command::SUCCESS;
    }
}
