<?php

namespace Modules\MedRegistry\Console;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Schema;
use Modules\MedRegistry\Services\PresetService;

/**
 * CLI/seeding twin of the setup wizard:
 *   php artisan medreg:apply-preset {business_id} {type_key} [--select=radiology --select=dental] [--user=1]
 */
class ApplyPresetCommand extends Command
{
    protected $signature = 'medreg:apply-preset
                            {business_id : ERP business id (tenant)}
                            {type_key : Business type preset key (hospital, polyclinic, …, custom)}
                            {--select=* : Optional/custom spec_keys to include}
                            {--user= : User id recorded as wizard completer}';

    protected $description = 'Apply a business-type module preset to a business (same engine as the setup wizard)';

    public function handle(PresetService $presets): int
    {
        if (! Schema::hasTable('medreg_modules') || ! Schema::hasTable('medreg_business_types')) {
            $this->error('MedRegistry tables missing — install the module first (/med-registry/install).');

            return 1;
        }

        $businessId = (int) $this->argument('business_id');
        $typeKey = (string) $this->argument('type_key');
        $selected = (array) $this->option('select');
        $userId = $this->option('user') !== null ? (int) $this->option('user') : null;

        try {
            $report = $presets->apply($businessId, $typeKey, $selected, $userId);
        } catch (\InvalidArgumentException $e) {
            $this->error($e->getMessage());

            return 1;
        }

        foreach ($report['enabled'] as $specKey => $moduleKeys) {
            $this->info(sprintf('enabled   %-28s → %s', $specKey, implode(', ', $moduleKeys)));
        }
        foreach ($report['dependency_added'] as $specKey) {
            $this->line(sprintf('dep-added %s', $specKey));
        }
        foreach ($report['skipped_missing'] as $specKey) {
            $this->warn(sprintf('skipped   %-28s (no installed host module)', $specKey));
        }

        $this->info(sprintf(
            'Preset "%s" applied to business #%d: %d enabled, %d dependencies auto-added, %d skipped.',
            $typeKey,
            $businessId,
            count($report['enabled']),
            count($report['dependency_added']),
            count($report['skipped_missing'])
        ));

        return 0;
    }
}
