<?php

namespace Corbital\ModuleManager\Console\Commands;

use Corbital\ModuleManager\Facades\ModuleManager;
use Illuminate\Console\Command;

class ModuleActivateCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'module:activate {name : The name of the module to activate} {--skip-migrations : Skip running migrations} {--skip-seeders : Skip running seeders}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Activate a module';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $name = $this->argument('name');
        $skipMigrations = $this->option('skip-migrations');
        $skipSeeders = $this->option('skip-seeders');

        if (! ModuleManager::has($name)) {
            $this->error("Module [{$name}] not found.");

            return 1;
        }

        if (ModuleManager::isActive($name)) {
            $this->info("Module [{$name}] is already active.");

            return 0;
        }

        // Override config settings based on command options
        if ($skipMigrations) {
            config(['modules.auto_migrations.enabled' => false]);
        }

        if ($skipSeeders) {
            config(['modules.auto_migrations.seed' => false]);
        }

        $startTime = microtime(true);

        if (ModuleManager::activate($name)) {
            $this->info("Module [{$name}] activated successfully.");

            // Show migration and seeder info if not skipped
            $autoMigrate = config('modules.auto_migrations.enabled', true);
            $autoSeed = config('modules.auto_migrations.seed', true);

            if ($autoMigrate) {
                $this->info("Migrations for module [{$name}] were processed automatically.");
            }

            if ($autoMigrate && $autoSeed) {
                $this->info("Seeders for module [{$name}] were run automatically.");
            }

            $elapsedTime = round(microtime(true) - $startTime, 2);
            $this->info("Activation completed in {$elapsedTime} seconds.");

            return 0;
        }

        $this->error("Failed to activate module [{$name}].");

        return 1;
    }
}
