<?php

namespace App\Http\Middleware;

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

class CheckModuleAccess
{
    /**
     * Handle an incoming request.
     * 
     * Check if the authenticated user has access to the specified portal.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     * @param  string  $moduleKey  The portal key to check 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 access to all portals
        if ($user->hasRole('super_admin')) {
            return $next($request);
        }

        // Check if user has access to this portal
        if (!$user->hasModuleAccess($moduleKey)) {
            return response()->json([
                'message' => 'Access denied. You do not have access to this portal.',
                'portal' => $moduleKey,
            ], 403);
        }

        return $next($request);
    }
}
