<?php

namespace App\Master\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
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): Response
    {
        if ($request->input('tenant') == 'none') {
            Artisan::call($request->input('command'));
            return \response('ok');
        }

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

        Artisan::call('tenants:run', $params);
        return \response('ok');
    }
}
