<?php

namespace App\Http\Middleware;

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

class RedirectToInstaller
{
    public function handle(Request $request, Closure $next): Response
    {
        $path = $request->path();

        if (Installation::isInstalled()) {
            if (str_starts_with($path, 'install')) {
                return redirect('/');
            }

            return $next($request);
        }

        if ($path === 'up' || str_starts_with($path, 'install')) {
            return $next($request);
        }

        if (str_starts_with($path, 'api/')) {
            return response()->json([
                'message' => 'Aplicación no instalada.',
                'install_url' => url('/install'),
            ], 503);
        }

        return redirect()->to('/install');
    }
}
