<?php

namespace App\Http\Middleware;

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

/**
 * Middleware: CheckMenuPermission
 *
 * Protects parent menu route groups.
 * Allows access if the user has legacy menu-level permissions OR at least
 * one granular scoped tab permission within the given menu.
 *
 * Route usage:
 *   ->middleware('menu-permission:global settings')
 *   ->middleware('menu-permission:mobile settings,manage')
 */
class CheckMenuPermission
{
    public function handle(Request $request, Closure $next, string $menu, string $action = 'view'): Response
    {
        if (! auth()->check()) {
            return $request->expectsJson()
                ? response()->json(['message' => 'Unauthenticated.'], 401)
                : redirect()->route('login');
        }

        $allowed = $action === 'manage'
            ? can_manage_any_tab($menu)
            : can_view_any_tab($menu);

        if (! $allowed) {
            return $request->expectsJson()
                ? response()->json(['message' => 'This action is unauthorized.'], 403)
                : abort(403, "Access denied to menu: {$menu}");
        }

        return $next($request);
    }
}
