<?php

namespace App\Http\Middleware;

use App\Services\Access\AccessService;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureMenuPermission
{
    public function __construct(
        protected AccessService $access
    ) {}

    public function handle(Request $request, Closure $next, string $menuSlug, string $permission): Response
    {
        $user = $request->user();
        $tenantId = $request->attributes->get('tenant_id');

        if (! $user || ! $this->access->hasMenuPermission($user, $menuSlug, $permission, $tenantId)) {
            return response()->json([
                'success' => false,
                'code' => 403,
                'message' => 'Anda tidak memiliki permission untuk tindakan ini.',
            ], 403);
        }

        return $next($request);
    }
}
