<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Tenant;
use Database\Seeders\Tenant\BulkProductSeeder;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;

class SeedTenantProducts extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'tenant:seed-products {tenant_id?} {--count=100}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Seed products for a specific tenant';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $tenantId = $this->argument('tenant_id');
        
        if ($tenantId) {
            $tenant = Tenant::find($tenantId);
        } else {
            $tenant = Tenant::first();
        }

        if (!$tenant) {
            $this->error('Tenant not found.');
            return;
        }

        $this->info("Seeding products for tenant: {$tenant->name} (ID: {$tenant->id})");

        // Switch Database Connection
        Config::set('database.connections.tenant.database', $tenant->database_name);
        DB::purge('tenant');
        DB::reconnect('tenant');
        DB::setDefaultConnection('tenant');

        $this->info("Database switched to {$tenant->database_name}");

        // Run Migrations to ensure schema is up to date
        $this->info("Running tenant migrations...");
        $this->call('migrate', [
            '--database' => 'tenant',
            '--path' => 'database/migrations/tenant',
            '--force' => true,
        ]);

        // Run Seeder
        $seeder = new BulkProductSeeder();
        
        // Inject this command so $this->command->info() works in Seeder
        if (method_exists($seeder, 'setCommand')) {
            $seeder->setCommand($this);
        } else {
            // Manually inject if protected property (via reflection if needed, but we used fallback)
            // But actually, Laravel Seeders don't easily allow injection unless invoked via $this->call() inside another seeder.
            // However, our BulkProductSeeder has a fallback check for $this->command.
            // Let's try to set it via reflection to be nice.
            try {
                $reflection = new \ReflectionClass($seeder);
                if ($reflection->hasProperty('command')) {
                    $property = $reflection->getProperty('command');
                    $property->setAccessible(true);
                    $property->setValue($seeder, $this);
                }
            } catch (\Exception $e) {
                // Ignore
            }
        }

        $seeder->run();
        
        $this->info("Done!");
    }
}
