<?php

namespace App\Http\Middleware;

use App\Services\CurrentContext;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

/**
 * Gates the master-control (central) Filament panel: requires an active
 * landlord on the `central` guard and marks the request as central context
 * (tenant scoping off). Tenant users can never reach these routes.
 *
 * docs/migration-plan.md §2: the source app's redirect('/sign-in') for a
 * missing admin is dropped — Filament's own Authenticate middleware
 * (->authGuard('central') on the panel) already redirects unauthenticated
 * requests to the panel's login page before this middleware runs. Only the
 * "authenticated but deactivated mid-session" case still needs handling here.
 */
class EnsureCentralAdmin
{
    public function __construct(private readonly CurrentContext $context) {}

    public function handle(Request $request, Closure $next): Response
    {
        $admin = Auth::guard('central')->user();

        if ($admin && ! $admin->is_active) {
            Auth::guard('central')->logout();
            $request->session()->invalidate();
            $request->session()->regenerateToken();

            return redirect()->route('filament.central.auth.login');
        }

        $this->context->markCentral();

        return $next($request);
    }
}
