<?php

namespace App\Http\Middleware;

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

class EnsureInstallationIsComplete
{
    public function __construct(protected InstallationService $installation)
    {
    }

    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next): Response
    {
        if ($this->shouldBypass($request)) {
            return $next($request);
        }

        $needsInstallation = $this->installation->needsInstallation();

        if ($needsInstallation) {
            $this->ensureInstallSafeSessionDriver();

            if (! $request->is('install', 'install/*')) {
                return redirect()->route('install.index');
            }
        } elseif ($request->is('install', 'install/*')) {
            return redirect()->route('dashboard');
        }

        return $next($request);
    }

    protected function shouldBypass(Request $request): bool
    {
        if ($request->is('up')) {
            return true;
        }

        if ($request->is('storage/*')) {
            return true;
        }

        if ($request->is('install/assets/*')) {
            return true;
        }

        return false;
    }

    protected function ensureInstallSafeSessionDriver(): void
    {
        if (config('session.driver') === 'database') {
            config()->set('session.driver', 'file');
        }
    }
}