<?php

namespace App\Http\Middleware;

use App\Models\User;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

class PreserveFrontendSessionDuringAdminLogout
{
    /**
     * Filament invalidates the whole session on admin logout. Because the
     * frontend and admin panel use separate guards, restore only the frontend
     * guard after Filament has cleared the admin guard.
     *
     * @param  Closure(Request): Response  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $frontendUser = $request->is('admin/logout') && Auth::guard('web')->check()
            ? Auth::guard('web')->user()
            : null;

        $response = $next($request);

        if ($frontendUser instanceof User) {
            Auth::guard('web')->login($frontendUser);
        }

        return $response;
    }
}
