<?php

namespace App\Master\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Mtc\MercuryDataModels\Tenant;

class CommandController extends Controller
{
    public function index(Request $request): array
    {
        return [
            'commands' => collect(Artisan::all())
                ->map(fn ($stuff, $key) => [
                    'name' => $key,
                    'id' => $key,
                ])
                ->sortBy(fn ($row) => $row['name'])
                ->values(),
            'tenants' => Tenant::query()
                ->whereNull('suspended_at')
                ->select(['name', 'id'])
                ->get()
                ->prepend(['name' => 'All', 'id' => 'all'])
                ->prepend(['name' => 'System command (not run for tenants)', 'id' => 'none']),
        ];
    }

    public function store(Request $request): array
    {
        if ($request->input('tenant') == 'none') {
            $exitCode = Artisan::call($request->input('command'));

            return [
                'exit_code' => $exitCode,
                'output' => Artisan::output(),
            ];
        }

        $params = [
            'commandname' => $request->input('command'),
        ];
        if ($request->input('tenant') !== 'all') {
            $params['--tenants'] = $request->input('tenant');
        }

        $exitCode = Artisan::call('tenants:run', $params);

        return [
            'exit_code' => $exitCode,
            'output' => Artisan::output(),
        ];
    }
}
