<?php

namespace App\Modules\Pilkades\Http\Middleware;

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

/**
 * Defense-in-depth check on top of DesaScope: verifies that any route-bound
 * model carrying a desa_id actually belongs to the logged-in Admin Desa's
 * own desa, even if a global scope was bypassed (e.g. withoutGlobalScope).
 */
class EnsureTenantAccess
{
    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();

        if ($user && $user->isAdminDesa()) {
            foreach ($request->route()->parameters() as $parameter) {
                if (is_object($parameter) && isset($parameter->desa_id) && $parameter->desa_id !== $user->desa_id) {
                    abort(403);
                }
            }
        }

        return $next($request);
    }
}
