<?php

namespace App\Command;

use App\Entity\Family;
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:family:create', description: 'Crée une famille pilote.')]
final class CreateFamilyCommand extends Command
{
    public function __construct(private readonly EntityManagerInterface $entityManager)
    {
        parent::__construct();
    }

    protected function configure(): void
    {
        $this
            ->addArgument('name', InputArgument::REQUIRED, 'Nom de la famille')
            ->addArgument('timezone', InputArgument::OPTIONAL, 'Timezone IANA', 'Europe/Paris');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $name = trim((string) $input->getArgument('name'));
        $timezone = (string) $input->getArgument('timezone');

        if ('' === $name || mb_strlen($name) > 120) {
            $output->writeln('<error>Le nom doit contenir entre 1 et 120 caractères.</error>');

            return Command::INVALID;
        }

        try {
            new \DateTimeZone($timezone);
        } catch (\Throwable) {
            $output->writeln('<error>Timezone IANA invalide.</error>');

            return Command::INVALID;
        }

        $family = new Family($name, $timezone);
        $this->entityManager->persist($family);
        $this->entityManager->flush();
        $output->writeln(sprintf('<info>Famille créée avec l’identifiant %d.</info>', $family->getId()));

        return Command::SUCCESS;
    }
}
