<?php

namespace App\Http\Middleware;

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

class CheckInstalled
{
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next): Response
    {
        $isInstalled = file_exists(storage_path('app/.installed'));
        $isInstallRoute = $request->is('install') || $request->is('install/*') || $request->is('install/*/*');

        if ($isInstalled) {
            // If already installed, block install wizard and redirect to admin/home
            if ($isInstallRoute) {
                return redirect('/admin');
            }
            return $next($request);
        }

        // If not installed, and not on the install wizard, redirect to install wizard
        if (!$isInstallRoute) {
            // Exclude API, health check, and sanctum requests to avoid breaking integrations
            if ($request->is('api/*') || $request->is('up') || $request->is('sanctum/*')) {
                return $next($request);
            }
            return redirect()->route('install.wizard');
        }

        return $next($request);
    }
}
