<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureApplicationIsInstalled
{
    public function handle(Request $request, Closure $next): Response
    {
        if (app()->environment('testing') || file_exists(storage_path('app/installed'))) {
            return $next($request);
        }
        if ($request->is('install', 'install/*', 'up')) {
            return $next($request);
        }
        if ($request->expectsJson()) {
            return response()->json(['message' => 'Application installation is required.'], 503);
        }

        return redirect()->route('install.welcome');
    }
}
