<?php

namespace App\Http\Middleware;

use App\Support\Installation;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Sends a freshly uploaded copy to the installer instead of a stack trace.
 *
 * Without this, the first visit to a new deployment hits a database that does
 * not exist yet and answers with a 500.
 */
class RedirectToInstaller
{
    public function handle(Request $request, Closure $next): Response
    {
        // The test suite builds its own schema and never runs the installer.
        if (app()->runningUnitTests() || Installation::isInstalled()) {
            return $next($request);
        }

        if ($request->is('instalar', 'instalar/*', 'up', 'build/*', 'images/*', 'storage/*')) {
            return $next($request);
        }

        return redirect('/instalar');
    }
}
