<?php

namespace App\Console\Commands;

use App\Console\RunForSuspendedTenants;
use Stancl\Tenancy\Commands\Run;

class TenantsRun extends Run
{
    /**
     * Execute the console command.
     */
    #[\Override]
    public function handle()
    {
        tenancy()->runForMultiple($this->option('tenants'), function ($tenant) {
            $result = $this->resolveCommand($this->argument('commandname'));
            if ($result instanceof RunForSuspendedTenants === false && !empty($tenant->suspended_at)) {
                $this->line("Skipping suspended tenant: {$tenant->getTenantKey()}");
                return;
            }

            $this->line("Tenant: {$tenant->getTenantKey()}");

            $callback = (fn ($prefix = '') => function ($arguments, $argument) use ($prefix) {
                [$key, $value] = explode('=', $argument, 2);
                $arguments[$prefix . $key] = $value;

                return $arguments;
            });

            // Turns ['foo=bar', 'abc=xyz=zzz'] into ['foo' => 'bar', 'abc' => 'xyz=zzz']
            $arguments = array_reduce($this->option('argument'), $callback(), []);

            // Turns ['foo=bar', 'abc=xyz=zzz'] into ['--foo' => 'bar', '--abc' => 'xyz=zzz']
            $options = array_reduce($this->option('option'), $callback('--'), []);

            // Run command
            $this->call($this->argument('commandname'), array_merge($arguments, $options));
        });
    }
}
