<?php

namespace App\Http\Middleware;

use Closure;
use Filament\Notifications\Notification;
use Illuminate\Http\Request;
use Joaopaulolndev\FilamentEditProfile\Pages\EditProfilePage;
use Symfony\Component\HttpFoundation\Response;

class EnsureProfileIsFilled
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        /** @var \App\Models\User */
        $user = $request->user();

        // 1. If user is not logged in, or profile is already complete, do nothing.
        // (Based on your logic: must_fill_profile == true means complete)
        if (! $user->must_fill_profile) {
            return $next($request);
        }

        // 3. Define the 'safe' routes
        $profilePageClass = EditProfilePage::class;
        $profilePageUrl = $profilePageClass::getUrl();

        /** @var \Filament\Panel */
        $panel = filament()->getCurrentPanel();

        $panelId = $panel->getId();
        $logoutRouteName = "filament.{$panelId}.auth.logout";

        // 4. Check for 'safe' conditions

        // Are they ALREADY on the profile page?
        // We check the full URL to be precise.
        $isProfilePage = $request->fullUrlIs($profilePageUrl);

        // Are they trying to log out?
        $isLoggingOut = $request->routeIs($logoutRouteName);

        // Is this an internal Livewire request?
        // This is the KEY to fixing the SPA redirect loop.
        $isLivewireRequest = $request->is('livewire/*');

        // 5. If they are on a safe route, let them proceed.
        if ($isProfilePage || $isLoggingOut || $isLivewireRequest) {
            return $next($request);
        }

        Notification::make()
            ->danger()
            ->title(__('Please update your profile'))
            ->send();

        // 6. If not, redirect them to the profile page.
        // Filament's SPA mode will intercept this 302 redirect
        // and navigate without a full page reload.
        return redirect($profilePageUrl);
    }
}
