<?php

namespace App\Http\Middleware;

use App\Services\InstallerService;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Gates every WEB route behind the install wizard until storage/app/installed.lock
 * exists (or we're in the test environment, which manages its own DB per test
 * and must never be redirected). /install itself and the health check /up are
 * always allowed through — InstallController handles the "already installed"
 * case itself so this middleware never has to distinguish it.
 */
class EnsureInstalled
{
    public function handle(Request $request, Closure $next): Response
    {
        $installer = app(InstallerService::class);

        if ($installer->isInstalled() || $request->is('install*') || $request->is('up')) {
            return $next($request);
        }

        return redirect('/install');
    }
}
