<?php

namespace App\Http\Middleware;

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

class CheckModuleAdmin
{
    /**
     * Handle an incoming request.
     * 
     * Check if the authenticated user has admin access to the specified portal.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     * @param  string  $moduleKey  The portal key to check admin access for (kept as moduleKey for backward compatibility)
     */
    public function handle(Request $request, Closure $next, string $moduleKey): Response
    {
        $user = $request->user();

        if (!$user) {
            return response()->json([
                'message' => 'Unauthenticated.',
            ], 401);
        }

        // Super admin has admin access to all portals
        if ($user->hasRole('super_admin')) {
            return $next($request);
        }

        // Check if user has admin access to this portal
        if (!$user->isModuleAdmin($moduleKey)) {
            return response()->json([
                'message' => 'Access denied. Admin privileges required for this portal.',
                'portal' => $moduleKey,
                'your_role' => $user->getModuleRoleScope($moduleKey) ?? 'none',
            ], 403);
        }

        return $next($request);
    }
}
