<?php

namespace App\Http\Middleware;

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

class EnsureInstalled
{
    /**
     * Handle an incoming request.
     *
     * @param  Closure(Request): (Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if (file_exists(storage_path('app/installed'))) {
            return $next($request);
        }

        if ($request->routeIs('install.*') || $request->is('install') || $request->is('install/*')) {
            return $next($request);
        }

        if ($request->expectsJson()) {
            return response()->json([
                'message' => 'ViZuTrade must be installed before this route can be used.',
            ], 503);
        }

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