<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureOnboardingCompleted
{
    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();
        $profile = $user?->profile;

        $done = (bool) ($profile?->onboarding_completed_at);
        $path = '/'.ltrim($request->path(), '/');

        if (! $done && $path !== '/onboarding') {
            return redirect()->route('app.onboarding');
        }

        if ($done && $path === '/onboarding') {
            return redirect()->route('app.home');
        }

        return $next($request);
    }
}

