<?php

namespace App\Http\Middleware;

use App\Enums\StatusEnum;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class CheckInstallation
{
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next): Response
    {

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

        // Skip check for API routes, assets, auth routes, etc.
        if ($request->is('api/*') ||
            $request->is('assets/*') ||
            $request->is('build/*') ||
            $request->is('storage/*') ||
            $request->is('login') ||
            $request->is('auth/*') ||
            $request->is('logout')) {
            return $next($request);
        }

        // Check if app is installed
        $isInstalled = env('APP_INSTALL', false);

        if (!$isInstalled) {
            // Redirect to installer - skip maintenance mode check when not installed
            // as database may not be available yet
            return redirect('/install');
        }

        return $next($request);
    }
}
