<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Support\ApiCenterSchema;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Artisan;
use Illuminate\View\View;
use Throwable;

class SetupController extends Controller
{
    public function index(ApiCenterSchema $schema): View
    {
        return view('admin.setup', [
            'missingTables' => $schema->missingTables(),
            'output' => session('migration_output'),
        ]);
    }

    public function migrate(): RedirectResponse
    {
        try {
            Artisan::call('migrate', ['--force' => true]);

            return redirect()
                ->route('admin.setup')
                ->with('status', 'Migration dijalankan.')
                ->with('migration_output', Artisan::output());
        } catch (Throwable $exception) {
            return redirect()
                ->route('admin.setup')
                ->withErrors(['migration' => $exception->getMessage()]);
        }
    }
}
