<?php

namespace App\Nexus\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class NexusAdminAuth
{
    /**
     * Protect all NEXUS dashboard routes.
     *
     * Checks:
     * 1. The admin is authenticated via the 'nexus' guard.
     * 2. The admin has role_id 1 (full admin — not editor, blogger, or agent).
     *
     * On pass: binds the authenticated admin to $request->nexusAdmin for use in controllers.
     * On fail: redirects to the NEXUS login page.
     */
    public function handle(Request $request, Closure $next)
    {
        if (!Auth::guard('nexus')->check()) {
            return redirect()->route('nexus.login')
                ->with('error', 'Please log in to access the NEXUS dashboard.');
        }

        $admin = Auth::guard('nexus')->user();

        if ((int) $admin->role_id !== 1) {
            Auth::guard('nexus')->logout();
            return redirect()->route('nexus.login')
                ->with('error', 'You do not have permission to access the NEXUS dashboard.');
        }

        // Bind admin to request so controllers can use $request->nexusAdmin directly
        $request->merge(['nexusAdmin' => $admin]);

        return $next($request);
    }
}
