<?php

namespace App\Config\Command;

use App\Config\Service\MaintenanceService;
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;
use Symfony\Component\Console\Style\SymfonyStyle;

/**
 * راه فرار از حالت تعمیرات وقتی پنل ادمین در دسترس نیست.
 *
 *   ddev exec php bin/console app:maintenance status
 *   ddev exec php bin/console app:maintenance off
 */
#[AsCommand(name: 'app:maintenance', description: 'Enable, disable or inspect maintenance mode')]
class MaintenanceCommand extends Command
{
    public function __construct(
        private readonly MaintenanceService     $maintenance,
        private readonly EntityManagerInterface $em,
    ) {
        parent::__construct();
    }

    protected function configure(): void
    {
        $this->addArgument('action', InputArgument::REQUIRED, 'on | off | status');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io     = new SymfonyStyle($input, $output);
        $action = strtolower((string) $input->getArgument('action'));

        if (!in_array($action, ['on', 'off', 'status'], true)) {
            $io->error(sprintf('Unknown action "%s". Use on, off or status.', $action));

            return Command::INVALID;
        }

        if ($action === 'status') {
            $state = $this->maintenance->getState();
            $io->definitionList(
                ['enabled' => $state['enabled'] ? 'yes' : 'no'],
                ['title' => $state['title']],
                ['message' => $state['message']],
                ['retry_after' => $state['retryAfter']],
                ['allowed_ips' => implode(', ', $state['allowedIps']) ?: '-'],
            );

            return Command::SUCCESS;
        }

        $action === 'on' ? $this->maintenance->enable() : $this->maintenance->disable();
        $this->em->flush();
        $this->maintenance->invalidate();

        $io->success(sprintf('Maintenance mode is now %s.', $action === 'on' ? 'ENABLED' : 'DISABLED'));

        return Command::SUCCESS;
    }
}
