<?php

namespace App\Http\Middleware;

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

/**
 * Gate for the SaaS control panel. Being logged in isn't enough — it has to
 * be the one platform-level operator account: is_root = true and
 * company_id = null. A company's own admin (is_admin = true, company_id
 * set) is rejected here even if they guess the URL.
 */
class EnsureIsRootAdmin
{
    public function handle(Request $request, Closure $next): Response
    {
        $user = Auth::user();

        if (!$user || !$user->is_root || $user->company_id !== null) {
            Auth::logout();

            return redirect()->route('saas-admin.login')->with('error', 'Please sign in as the SaaS administrator.');
        }

        return $next($request);
    }
}
