<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Tenant;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Database\Migrations\Migrator;

class MigrateTenant extends Command
{
    protected $signature = 'tenant:migrate-all';
    protected $description = 'Run migrations for all tenants';

    public function handle()
    {
        $tenants = Tenant::all();
        
        if ($tenants->isEmpty()) {
            $this->error('No tenants found!');
            return;
        }

        foreach ($tenants as $tenant) {
            $this->info("Migrating database for tenant: {$tenant->name} ({$tenant->database_name})");

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

            // Store the original default connection and set to tenant
            $originalDefaultConnection = Config::get('database.default');
            Config::set('database.default', 'tenant');
            
            // Run migrations for the tenant connection and path
            Artisan::call('migrate', [
                '--path' => 'database/migrations/tenant',
                '--database' => 'tenant',
                '--force' => true,
            ]);

            $this->info(Artisan::output());

            // Restore original default connection
            Config::set('database.default', $originalDefaultConnection);
        }

        $this->info('All tenant migrations completed.');
    }
}
