<?php

namespace App\Http\Middleware;

use App\Models\Business;
use Closure;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureTenantRouteModelsBelongToBusiness
{
    public function handle(Request $request, Closure $next): Response
    {
        $business = $request->attributes->get('current_business');

        if (! $business instanceof Business || $request->user()?->isSuperAdmin()) {
            return $next($request);
        }

        foreach ($request->route()?->parameters() ?? [] as $parameter) {
            if (! $parameter instanceof Model) {
                continue;
            }

            if ($parameter instanceof Business) {
                abort_unless((int) $parameter->getKey() === (int) $business->getKey(), 404);
                continue;
            }

            if (array_key_exists('business_id', $parameter->getAttributes())) {
                abort_unless((int) $parameter->getAttribute('business_id') === (int) $business->getKey(), 404);
            }
        }

        return $next($request);
    }
}
