<?php

namespace App\Http\Middleware;

use App\Services\Installer\InstallerProgressValidator;
use App\Services\Installer\WizardSessionStore;
use App\Support\InstallationState;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureInstallerProgress
{
    public function __construct(
        private readonly InstallationState $installationState,
        private readonly WizardSessionStore $wizardSessionStore,
    ) {}

    public function handle(Request $request, Closure $next, string $step): Response
    {
        if ($this->installationState->isInstalled()) {
            return $next($request);
        }

        $redirect = InstallerProgressValidator::redirectIfIncomplete(
            $step,
            $this->wizardSessionStore->get(),
        );

        if ($redirect !== null) {
            return $redirect;
        }

        return $next($request);
    }
}
