<?php

namespace App\Http\Middleware;

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

class UseInstallerSession
{
    public function __construct(
        private readonly InstallationState $installationState,
        private readonly WizardSessionStore $wizardSessionStore,
        private readonly InstallerDatabaseConfigurator $databaseConfigurator,
        private readonly EnvWriter $envWriter,
    ) {}

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

        $this->envWriter->prepareForInstallation();

        $state = $this->wizardSessionStore->get();

        if ($state->migrationsRun && $state->dbConnection) {
            $this->databaseConfigurator->apply($state);
        }

        config([
            'session.driver' => 'file',
            'cache.default' => 'file',
            'queue.default' => 'sync',
        ]);

        return $next($request);
    }
}
