<?php

declare(strict_types=1);

namespace App\Command;

use App\Entity\User;
use App\Repository\UserRepository;
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;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;

#[AsCommand(
    name: 'app:user:seed',
    description: 'Create a default application user if it does not exist yet.',
)]
class SeedUserCommand extends Command
{
    public function __construct(
        private readonly UserRepository $userRepository,
        private readonly EntityManagerInterface $entityManager,
        private readonly UserPasswordHasherInterface $passwordHasher,
    ) {
        parent::__construct();
    }

    protected function configure(): void
    {
        $this
            ->addOption('email', null, InputOption::VALUE_OPTIONAL, 'Seed user email')
            ->addOption('password', null, InputOption::VALUE_OPTIONAL, 'Seed user password');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);

        $emailOption = trim((string) $input->getOption('email'));
        $passwordOption = (string) $input->getOption('password');

        $email = mb_strtolower($emailOption !== '' ? $emailOption : ((string) (getenv('APP_SEED_USER_EMAIL') ?: 'demo@example.com')));
        $plainPassword = $passwordOption !== '' ? $passwordOption : (string) (getenv('APP_SEED_USER_PASSWORD') ?: 'demo12345');

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $io->error('Seed user email is invalid.');

            return Command::FAILURE;
        }

        if (mb_strlen($plainPassword) < 8) {
            $io->error('Seed user password must be at least 8 characters.');

            return Command::FAILURE;
        }

        if ($this->userRepository->findOneByEmail($email) instanceof User) {
            $io->text(sprintf('Seed user "%s" already exists.', $email));

            return Command::SUCCESS;
        }

        $user = new User($email);
        $user->setPassword($this->passwordHasher->hashPassword($user, $plainPassword));
        $this->entityManager->persist($user);
        $this->entityManager->flush();

        $io->success(sprintf('Seed user "%s" created.', $email));

        return Command::SUCCESS;
    }
}
