<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

// ══════════════════════════════════════════════════════════════════
//  EnsureAdmin Middleware
//
//  Protects all admin routes.
//  Applied AFTER the 'auth' middleware — so we know
//  the user is logged in before we check their role.
//
//  If the user is not an admin:
//    - Returns 403 Forbidden
//    - Never reveals what the admin panel contains
//    - Never redirects to the admin login (no such thing —
//      admins use the same login as members)
// ══════════════════════════════════════════════════════════════════

class EnsureAdmin
{
    public function handle(Request $request, Closure $next): Response
    {
        // Double-check user is authenticated
        // (should already be guaranteed by 'auth' middleware)
        if (! auth()->check()) {
            return redirect()->route('login');
        }

        // Check role
        if (! auth()->user()->isAdmin()) {
            abort(403, 'You do not have permission to access this area.');
        }

        return $next($request);
    }
}
