<?php

declare(strict_types=1);

namespace app\vendor\apexl\io\src\Io\modules\system\commands;

use apexl\Io\exceptions\RecordNotFoundException;
use apexl\Io\interfaces\IoModuleInterface;
use apexl\Io\modules\system\services\ModuleClassResolver;
use apexl\Vault\Vault;
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\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use function apexl\Io\assertInstanceOf;

#[AsCommand(name: 'modules:activate ', description: 'Activate a module')]
class ModuleActivateCommand extends DaedalusCommand
{
    private SymfonyStyle $io;
    private InputInterface $input;

    public function __construct(
        private readonly Vault $db,
        private readonly ModuleClassResolver $classResolver,
        ?string $name = null
    ) {
        parent::__construct($name);
    }

    protected function configure(): void
    {
        $this->addArgument('module', InputArgument::REQUIRED, 'The module to activate');
        $this->addOption('weight', 'w', InputOption::VALUE_OPTIONAL, 'Module weight', 1);
    }

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

        try {
            $moduleClass = $this->classResolver->resolve($module);

            $this->activateModule($moduleClass);

            $this->io->success(sprintf('Activated %s', $moduleClass));

            return Command::SUCCESS;
        } catch (RecordNotFoundException $e) {
            $this->io->error(sprintf('Could not resolve module `%s`: %s', $module, $e->getMessage()));

            return Command::FAILURE;
        }
    }

    private function activateModule(string $moduleClass): void
    {
        $result = $this->db->select('modules')
            ->fields('installed')
            ->where('module', $moduleClass)
            ->execute()
            ->fetch();

        if (!$result) {
            $this->insertModule($moduleClass);
            return;
        }

        if ($result->installed === 1) {
            $this->io->warning(sprintf('Module `%s` already activated', $moduleClass));
            return;
        }

        $this->updateModule($moduleClass);
    }

    private function insertModule(string $moduleClass): void
    {
        $this->db->insert('modules')
            ->fields([
                'module' => $moduleClass,
                'weight' => $this->input->getOption('weight'),
                'installed' => 1,
                'lastInstallDate' => time(),
            ])->execute();
    }

    private function updateModule(string $moduleClass)
    {
        $this->db->update('modules')
            ->fields([
                'weight' => $this->input->getOption('weight'),
                'installed' => 1,
                'lastInstallDate' => time(),
            ])
            ->where('module', $moduleClass)
            ->execute();

    }

    /** @return class-string<IoModuleInterface>
     * @throws RecordNotFoundException
     */
    private function resolveModuleClass(string $candidate): string
    {
        if (class_exists($candidate)) {
            assertInstanceOf($candidate, IoModuleInterface::class);

            if ($this->io->isVerbose()) {
                $this->io->info(sprintf('Found %s', $candidate));
            }

            return $candidate;
        }

        $class = sprintf('apexl\Io\modules\%1$s\%1$sModule', $candidate);

        if ($this->io->isVerbose()) {
            $this->io->info(sprintf('Built class string `%s` from `%s`', $class, $candidate));
        }

        if (class_exists($class)) {
            assertInstanceOf($class, IoModuleInterface::class);

            if ($this->io->isVerbose()) {
                $this->io->info(sprintf('Found %s', $class));
            }

            return $class;
        }

        throw new RecordNotFoundException();
    }
}
