<?php

declare(strict_types=1);

namespace BotGuard\Middleware;

use BotGuard\Controllers\Install\InstallController;
use BotGuard\Core\Request;
use BotGuard\Core\Response;
use Closure;

/**
 * Gates the application on installation state.
 *
 * Before installation, every request (except the wizard itself and static
 * assets) is redirected to /install. After installation, the wizard routes are
 * sealed off (redirected home) so they cannot be replayed — the only exception
 * is /install/finish, shown once immediately after a successful install.
 */
final class SetupMiddleware implements MiddlewareInterface
{
    public function handle(Request $request, Closure $next): Response
    {
        $path = $request->path();
        $isInstallPath = $path === '/install' || str_starts_with($path, '/install/');
        $isAsset = str_starts_with($path, '/assets');

        if (! InstallController::isInstalled()) {
            if ($isInstallPath || $isAsset) {
                return $next($request);
            }

            if ($request->wantsJson()) {
                return Response::json(['error' => 'Application not installed.', 'install_url' => '/install'], 503);
            }

            return Response::redirect('/install');
        }

        // Installed: prevent re-running the wizard.
        if ($isInstallPath && $path !== '/install/finish') {
            return Response::redirect('/');
        }

        return $next($request);
    }
}
