<?php

namespace App\Console\Commands;

use App\Services\TenantBootstrapper;
use Illuminate\Console\Attributes\AsCommand;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

#[AsCommand(name: 'tenants:bootstrap', description: 'Bootstrap menus/capability/categories/settings for tenant(s)')]
class TenantsBootstrap extends Command
{
    // 라라벨 12에서도 $signature 사용 가능 (옵션 기본값 포함)
    protected $signature = 'tenants:bootstrap
                            {--tenant_id= : Target tenant id}
                            {--all : Apply to all tenants}
                            {--recipe=STANDARD : Recipe (STANDARD|LITE|...)}';

    public function handle(TenantBootstrapper $svc): int
    {
        $recipe = (string) $this->option('recipe');
        $tenantId = $this->option('tenant_id');

        if ($this->option('all')) {
            $ids = DB::table('tenants')->pluck('id')->all();
        } elseif ($tenantId) {
            $ids = [(int) $tenantId];
        } else {
            $this->error('Provide --tenant_id=ID or --all');

            return self::FAILURE;
        }

        if (empty($ids)) {
            $this->warn('No tenant to bootstrap.');

            return self::SUCCESS;
        }

        foreach ($ids as $id) {
            $this->line("Bootstrapping tenant {$id} with recipe {$recipe} …");
            $svc->bootstrap((int) $id, $recipe);
            $this->info("Done tenant {$id}");
        }

        return self::SUCCESS;
    }
}
