<?php

namespace App\Console\Commands;

use App\Services\Installer\WizardSessionStore;
use App\Services\Module\ModuleUninstallService;
use App\Support\EnvWriter;
use App\Support\InstallationState;
use Illuminate\Console\Command;
use Illuminate\Console\ConfirmableTrait;
use Illuminate\Support\Facades\Schema;

class ResetInstallationCommand extends Command
{
    use ConfirmableTrait;

    protected $signature = 'install:reset
                            {--force : Reset without confirmation}
                            {--with-database : Drop all tables and re-run migrations}';

    protected $description = 'Reset the installation lock, uninstall marketplace modules, and clear wizard state';

    public function handle(
        InstallationState $installationState,
        WizardSessionStore $wizardSessionStore,
        EnvWriter $envWriter,
        ModuleUninstallService $moduleUninstallService,
    ): int {
        if (! $this->confirmToProceed()) {
            return self::FAILURE;
        }

        if ($this->option('with-database') && ! $this->confirmDatabaseReset()) {
            return self::FAILURE;
        }

        $wasInstalled = $installationState->isInstalled();
        $uninstalledModules = $this->uninstallMarketplaceModules($moduleUninstallService);

        $installationState->clear();
        $wizardSessionStore->clear();

        if ($envWriter->exists()) {
            $envWriter->set('APP_INSTALLED', 'false');
        }

        if ($this->option('with-database')) {
            $this->call('migrate:fresh', ['--force' => true]);
        }

        if ($wasInstalled) {
            $message = 'Installation reset. Visit /install to run the wizard again.';
        } else {
            $message = 'Installer state cleared. Visit /install to begin setup.';
        }

        if ($uninstalledModules > 0) {
            $message .= " Uninstalled {$uninstalledModules} marketplace module(s).";
        }

        $this->components->info($message);

        return self::SUCCESS;
    }

    private function uninstallMarketplaceModules(ModuleUninstallService $moduleUninstallService): int
    {
        if (! Schema::hasTable('installed_modules')) {
            return 0;
        }

        return $moduleUninstallService->uninstallAll(force: true);
    }

    protected function confirmToProceed(): bool
    {
        if ($this->option('force')) {
            return true;
        }

        $this->components->warn('This will remove the installation lock, uninstall all marketplace modules, and clear any in-progress wizard state.');

        return $this->confirm('Do you want to reset the installation?', false);
    }

    protected function confirmDatabaseReset(): bool
    {
        if ($this->option('force')) {
            return true;
        }

        $this->components->warn('All database tables will be dropped and recreated.');

        return $this->confirm('Do you want to reset the database as well?', false);
    }
}
